Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elvis operator in a casting invocation chain

The elvis operator, aka null-conditional operator, is massively cool.

In LINQ queries it works great in concert with the null-coalescing "??" operator.

Somedata.Where(dt=>(dt?.Inner?.InnerMost?.Include=="Yes")??false);

But what do you do if you need to cast the intermediate values?

For one link in the chain, it works out fine.

Somedata.Where(dt=>(
     ((InnerClass)dt?.Inner)
     ?.InnerMost)?.Include=="Yes")
     ??false);

But with additional necessary casts the cast and invocation are "driven apart".

Somedata.Where(dt=>(
     ((InnerMostClass)            <=== Cast
     ((InnerClass)dt?.Inner)
     ?.InnerMost)?.Include=="Yes"))         <=== Use
     ??false);

Probably messed up the the parenthesis more than once here, but I hope you get the idea.

Though this "trainwreck" invocation chain is a code smell, is there a more expressive way of doing this to improve succinctness and clarity?

like image 594
Tormod Avatar asked Nov 09 '22 21:11

Tormod


1 Answers

You can keep chaining and prevent the parenthesis by using a very simple extension method:

dt?.Inner.As<InnerClass>()?.InnerMost.As<InnerMostClass>()?.Include == "Yes"

With the extension method defined like this:

public static class ObjectExtensions
{
    public static T As<T>(this object obj) where T : class
    {
        return obj as T;
    }
}
like image 103
mnwsmit Avatar answered Nov 14 '22 23:11

mnwsmit