Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 262
  • Last Modified:

?? operator

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?
0
allelopath
Asked:
allelopath
  • 2
  • 2
3 Solutions
 
Gerwin Jansen, EE MVETopic Advisor 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]).
0
 
mvdeveloperCommented:
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.
0
 
allelopathAuthor Commented:
So, is there a difference between:
- assigning x to y when x is null
- assigning null to y
0
 
mvdeveloperCommented:
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.
0
 
allelopathAuthor 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.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now