In functional languages, there is often a monad Maybethat allows you to associate several calls with an object and return the full expression None/ null, if any part of the chain does not matter, but not typical NullReferenceException, you get to C # by a chain of calls, where one object can be zero .
This can be trivially implemented by writing Maybe<T>with some extension methods to allow similar behavior in C # using queries that can be useful when processing XML with additional elements / attributes, for example.
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 awkward and unintuitive, as people use to process sequences in Linq, not single elements, and in the end it leaves you Maybe<T>, not T. Will the conditional de-link operator (e.g. ..) be useful enough to turn it into a language? eg.
var val = doc.Elements("foo").FirstOrDefault()..Attribute("bar")..Value;
The conditional de link will expand to approximately:
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 see that this can lead to terrible abuse, for example, when used ..everywhere to avoid NullReferenceException, but, on the other hand, when used correctly, it can be very convenient in quite a few situations. Thoughts?
source
share