I recently found that we can use ?? operator to check nulls. Please check the below code samples:
var res = data ?? new data();
This is
Based on Bob's answer
public object nullCoalesce(object a, object b, object c)
{
return a ?? b ?? c;
}
public object ternary(object a, object b, object c)
{
return a != null ? a : b != null ? b : c;
}
public object ifThenElse(object a, object b, object c)
{
if (a != null)
return a;
else if (b != null)
return b;
else
return c;
}
... this is the IL from release builds ...
.method public hidebysig instance object nullCoalesce(
object a,
object b,
object c) cil managed
{
.maxstack 8
L_0000: ldarg.1
L_0001: dup
L_0002: brtrue.s L_000b
L_0004: pop
L_0005: ldarg.2
L_0006: dup
L_0007: brtrue.s L_000b
L_0009: pop
L_000a: ldarg.3
L_000b: ret
}
.method public hidebysig instance object ternary(
object a,
object b,
object c) cil managed
{
.maxstack 8
L_0000: ldarg.1
L_0001: brtrue.s L_000a
L_0003: ldarg.2
L_0004: brtrue.s L_0008
L_0006: ldarg.3
L_0007: ret
L_0008: ldarg.2
L_0009: ret
L_000a: ldarg.1
L_000b: ret
}
.method public hidebysig instance object ifThenElse(
object a,
object b,
object c) cil managed
{
.maxstack 8
L_0000: ldarg.1
L_0001: brfalse.s L_0005
L_0003: ldarg.1
L_0004: ret
L_0005: ldarg.2
L_0006: brfalse.s L_000a
L_0008: ldarg.2
L_0009: ret
L_000a: ldarg.3
L_000b: ret
}