Search code examples
c#operatorsnull-coalescing-operatornull-coalescing

What do you think about ??= operator in C#?


Do you think that C# will support something like ??= operator?

Instead of this:

if (list == null)
  list = new List<int>();

It might be possible to write:

list ??= new List<int>();

Now, I could use (but it seems to me not well readable):

list = list ?? new List<int>();

Solution

  • I have always wanted something like this. I would use it far more often than the ?? by itself.

    What I REALLY want, though, is a form of operator that lets you dereference the object only if non null. To replace this:

        int count = (list != null)? list.Count : 0
    

    with something like this:

        int count = list??.Count : 0
    

    Which would be especially useful for me with long chains of references (bad design, I know), but for example

        int count = foo??.bar??.baz??.list??.Count : 0
    

    This isn't currently possible with ?? because you can only say "assign to foo, or an alternative if null" but not "assign to a property of foo, or an alternative if null."