Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of ?? operator (null-coalescing operator)

I use ?? operator very heavily in my code. But today I just came across a question.

Here the code which I use for ?? operator

private List<string> _names;
public List<string> Names
{
    get { return _names ?? (_names = new List<string>()); }
}

But in some locations I have seen this code as well.

private List<string> _names;
public List<string> Names
{
    get { return _names ?? new List<string>(); }
}

What is real difference between these codes. In one I am assigning _names = new List() while in other I am just doing new List().

like image 653
fhnaseer Avatar asked Dec 15 '25 12:12

fhnaseer


1 Answers

The only difference I see is in first case your variable _names will contain a new empty list while in second it does not. In both cases value returned will be same.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!