Search code examples
c#.netnull-coalescing-operator

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


Solution

  • in second case you not assign _names with new List<string>(), if _names null, every time when you call Names it will create new List<string>(), but in first case new List<string>() create ones.