We help IT Professionals succeed at work.

?? operator

allelopath
allelopath asked
on
I've come across this line of code:
WorkItem.State[States.Permit] = myState.Permit ?? null;

Open in new window

The documentation shows:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

Open in new window

so to translate the first statement to y and x:
y = x ?? null;

Open in new window

which is to say, y = x, unless x is null, in which case y = null

Is the ?? necessary here?
Comment
Watch Question

Gerwin Jansen, EE MVETopic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2016
Commented:
From your reasoning, it looks to be not necessary but:

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

So if mystate.permit is not null, it returns mystate.permit else it returns null (and assigns to workitem.state[states.permit]).
Simple answer - No.

The only thing I can think of is whether the programmer was trying to cover the case when myState is null as well. But that won't work.

Author

Commented:
So, is there a difference between:
- assigning x to y when x is null
- assigning null to y
Only in so far as if it is a reference type, having an open reference to myState.permit might stop myState from being garbage collected.

But I would have thought the fact that it is null would cause the gc to treat them the same.

Author

Commented:
>> trying to cover the case when myState is null as well. But that won't work.
Having thought about it for a minute, I would bet that this is indeed the original intent.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.