C# – Property-coalescing operator for C#

ccode smellnull

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

Best Answer

I very much want a C# language feature that lets me safely do x.Prop.SomeOtherProp.ThirdProp without having to check each of those for null. In one codebase where I had to do those sorts of "deep property traversals" a lot, I wrote an extension method called Navigate that swallowed NullReferenceExceptions and instead returned a default value. So I could do something like this:

var propVal = myThing.Navigate(x => x.PropOne.PropTwo.PropThree.PropFour, defaultValue);

The downside of this is that it has a different code smell: swallowed exceptions. If you wanted to do something like this "right", you could take the lamdba as an expression, and modify the expression on the fly to add the null checks around each property accessor. I went for "quick and dirty" and didn't implement it this "better" way. But maybe when I have some spare thought cycles I'll revisit this and post it somewhere.

To more directly answer your question, I'm guessing the reason this isn't a feature is because the cost of implementing the feature exceeds the benefit from having the feature. The C# team has to pick and choose which features to focus on, and this one hasn't floated to the top yet. Just a guess though I don't have any insider info.

Related Topic