What do you think about ??= operator in C#? [closed]
-
23-09-2019 - |
Question
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."
OTHER TIPS
Personally I think only the second expansion makes sense (in terms of keeping along the same line as +=
etc):
list = list ?? new List<int>();
but to be honest I find it a little bit unnecessary. People usually "get" i += 5;
, but tend to have a problem with null-coalescing (??
). Add a null-coalescing-assignment operator and... well, I don't see it ending well.
Personally I favor the original code:
if(list == null) { list = new List<int>(); }
....
Also - consider: in all the other +=
, -=
etc - the right hand side is always evaluated. In this case it wouldn't be (in some cases). That adds even more confusion. By which I mean:
i += SomethingCriticalThatMustBeCalled(); // fine - always runs
j ??= SomethingElseCriticalThatMustBeCalled(); // is this run? if j != null?
A trick I found somewhere here on stackoverflow was to do something like this...
private List<string> myList;
public List<string> MyProp
{
get { return myList ?? (myList= new List<string>()); }
}
... you maybe able to use similar lazy eval in your code.
I like it - it is a nice, succinct way to express a lazy-loading expression. Whether or not it gets added to language is another thing altogether - as Eric Lippert loves to point out, new features require significant amounts of work to implement and as such they must contribute a significant net positive to the language in order to be included.
Unless I read your question wrong, that operator does exist in C#: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx