In functional languages there is often a Maybe
monad which allows you to chain multiple calls on an object and have the entire expression return None
/null
if any part of the chain evaluates to nothing, rather than the typical NullReferenceException
you'd get in C# by chaining calls where one object could be null.
This can be trivially implemented by writing a Maybe<T>
with some extension methods to allow similar behaviour in C# using query comprehensions, which can be useful when processing XML with optional elements/attributes e.g.
var val = from foo in doc.Elements("foo").FirstOrDefault().ToMaybe()
from bar in foo.Attribute("bar").ToMaybe()
select bar.Value;
But this syntax is a bit clunky and unintuitive as people are used to dealing with sequences in Linq rather than single elements, and it leaves you with a Maybe<T>
rather than a T
at the end. Would a conditional de-reference operator (e.g. ..
) be sufficiently useful to make it into the language? e.g.
var val = doc.Elements("foo").FirstOrDefault()..Attribute("bar")..Value;
The conditional de-reference would expand to something like:
object val;
var foo = doc.Elements("foo").FirstOrDefault();
if (foo != null)
{
var bar = foo.Attribute("bar");
if (bar != null)
{
val = bar.Value;
}
else
{
val = null;
}
}
I can see that this could potentially lead to terrible abuse like using ..
everywhere to avoid a NullReferenceException
, but on the other hand when used properly it could be very handy in quite a few situations. Thoughts?