Elvis operator in a casting invocation chain

1.1k Views Asked by At

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?

1

There are 1 best solutions below

1
On

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;
    }
}