Would a conditional de-link operator be good in C #?

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?

+5
source share
4 answers

. , , , , , .

+1

, . - , ( , , - , ):

public static IEnumerable<T> Maybe<T>(this IEnumerable<T> lhs, Func<IEnumerable<T>, T> rhs)
{
  if (lhs != null)
  {
    return rhs(lhs);
  }

  return lhs;
}
0

, NUllable .

T .

(TBH langauge , F #)

You can simplify the code, set the value of val to null and exclude else branches.

0
source

I can see the potential usefulness, but apart from a minor performance impact, if the elements are often null, why not just surround the code block with a try..catch block to throw a NullReferenceException?

-2
source

All Articles