Syntax for handling null values nicely
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. :)
No comments:
Post a Comment