Reputation: 1281
Is there a difference between using ??
and if (foo == null) {...} else {...}
in C#?
Upvotes: 0
Views: 63
Reputation: 127543
The ??
operator will only evaluate your value once, your version likely would evaluate it multiple times.
so
var baz = foo ?? bar;
should get evaluated as
var tmp = foo;
if(tmp == null)
{
tmp = bar;
}
var baz = tmp;
This is difference is important when foo
is a function or a property which has a side effect in the getter.
private int _counter1 = 0;
private int _counter2 = 0;
private string Example1()
{
_counter1++;
if(_counter1 % 2 == 0)
return _counter1.ToString();
else
return null;
}
private string Example2()
{
_counter2++;
return _counter2.ToString();
}
Every time you do a var result = Example1() ?? Example2()
the value of _counter1
should only go up by one and the value of _counter2
should only go up every other call.
//Equivalent if statement
var tmp = Example1();
if(tmp == null)
{
tmp = Example2();
}
var result = tmp;
Upvotes: 6