简体   繁体   中英

What is the difference between using ?? and an if not null block in C#?

Is there a difference between using ?? and if (foo == null) {...} else {...} in C#?

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() 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM