3

When returning an object that may be null but mustn't I usually go with the (what its proper name?!) very-surprised operator: ?? like so.

return hazaa ?? new Hazaa();

The problem arises when I return a property of the object (in case it exists) and some default value otherwise. Not that the check of nullness is to be done on the parent object. Today I do like so.

return hazaa != null
  ? hazaa.Property
  : String.Empty;

I think it's a less than optimal syntax and I'd like it more compact (but still easily understandable, given that the property is implemented appropriately) like so.

return (hazaa ?? new Hazaa()).Property;

However, I dislike the parentheses and I'm looking for a syntax that omits them, still being compact. Is there such a thing in C#? I'm looking for something like this.

return hazaa ?.Property :String.Empty;

And, spinning on the thought, something like this.

return hazaa ?.Property :.BackUpProperty;

I could create my own property layer that gives me such behavior but that's just hiding the issue. :)

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

2 Answers2

3

A Maybe monad might be a possible alternative.

Depending on the implementation it could look like this:

May.Be(hazaa, x => x.Property, string.Empty);

or

May.Be(hazaa).Select(x => x.Property, string.Empty);
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

If you are interested in this topic, you should do some reading on monads. On the Maybe monad in particular. This should get you started: http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/

There is no inbuilt syntax to simplify null checks in C#, sadly.

Bridge
  • 29,818
  • 9
  • 60
  • 82
Nikita B
  • 3,303
  • 1
  • 23
  • 41