The null-coalescing operator in c# allows you to shorten the code
if (_mywidget == null)
return new Widget();
else
return _mywidget;
Down to:
return _mywidget ?? new Widget();
I keep finding that a useful operator I'd like to have in C# would be one that allowed you to return a property of an object, or some other value if the object is null. So I'd like to replace
if (_mywidget == null)
return 5;
else
return _mywidget.Length;
With:
return _mywidget.Length ??! 5;
I can't help thinking that there must be some reason for this operator not to exist. Is it a code smell? Is there some better way to write this? (I'm aware of the null object pattern but it seems overkill to use it to replace these four lines of code.)
??!
is an operator in C++. :-)