C# basics: the difference between the ?: and ?? operators for null value checks
Posted: (EET/GMT+2)
Today, I wanted to blog about C#'s two useful operators, the "question-mark operators", i.e. the ?: operator (officially, the conditional operator) and the ?? operator, officially the null-coalescing operator.
The question is, what is the difference of the following two version of code:
string s = null; string output = (s == null) ? s : "(none)"
...and:
string output = s ?? "(none)"
In both of the above code versions, the variable "s" value is checked against null. If the value is null, then the result of the output string is "(none)".
Are these code versions any different? In this situation, they are not. Thus, it is essentially the same which version you use, the end result is the same. Also, the generated IL code is almost exactly the same. Here's dump from ILDASM.
First code version, using the ?: operator:
IL_0003: ldloc.0 IL_0004: dup IL_0005: brtrue.s IL_000d IL_0007: pop IL_0008: ldstr "(none)" IL_000d: stloc.1
And here's the emitted code when using the ?? operator:
IL_0014: ldloc.0 IL_0015: brfalse.s IL_001e IL_0017: ldstr "(none)" IL_001c: br.s IL_001f IL_001e: ldloc.0 IL_001f: stloc.1
Hope this clarifies the situation!