Are oneline if statement checking for null the same thing as the null-coalescing operator?

501 views Asked by At

I'm currently reading some (old) mapping code from one domain model to another, and i've stumbled accross something. EDIT: The difference between these domain models are their vesions. So alot of fields are named with the suffi V2 or V3 for instance. the MigrateToLatest methods, are simply mapping functions that maps between the types. So for instance if MigrateToLatest is called on a list of element, each element calls it's MigrateToLatest method. If these elements again contains complex elements, these again calls MigrateToLatest.

Okay so theres alot of code that looks like this going on.

 return this.SomeFieldV3!= null ? this.SomeFieldV2.MigrateToLatest() : null;

But theres also some coe that looks like this

return this.SomeField = this.SomeField ?? null,

So I understand that in the first line, in order to avoid a null pointer exception, it's first checked that the field is not null, and else null is returned. But i don't really understand the second line - or at least I dont think i do...

I looked the ?? operator up, at MSDN, but it seems superfluous in this context. If the value is not null, then the field is returned, and if the field is not, null is returned anyway? :-S

To me it looks like these two lines are doing the same thing, but since I know for a fact that the same programmer wrote the entire mapping class, I can't shake the feeling that they are different - why else would someone choose to do the same thing in two different ways?

So are these two lines of code doing the same thing or not? And if they are which are the preferred use, and if they are not can someone please elaborate on the difference

1

There are 1 answers

0
Vineeth Chitteti On BEST ANSWER

Read this answer to know more about null-coalescing operator.

stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c

I can only say that they are doing the same thing, but first one is better and faster.

Because in the second case the RHS evaluates to this:

this.SomeField ?? null

Is equivalent to

this.SomeField != null ? this.SomeField : null;

So the entire code

return this.SomeField = this.SomeField ?? null;

evaluates to

return this.SomeField = this.SomeField != null ? this.SomeField : null;

As you can see there is code repetition which can be minimized by only using this:

return this.SomeField ?? null;