Elvis operator in casting call chain

The elvis operator, as a null-condition operator, is massively cool.

In LINQ queries, it works great along with zero coalescing "??" Operator.

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

But what will you do if you need to specify intermediate values?

For a single link in a chain, it works great.

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

But with additional casts needed casting and calling are "spaced".

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

Probably messed up the parentheses several times, but I hope you understand this idea.

Although this trainwreck call chain is a code smell, is there a more expressive way to do this to improve conciseness and clarity?

+5
source share
1 answer

You can save the chain and prevent parentheses using a very simple extension method:

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

Using the extension method defined as follows:

 public static class ObjectExtensions { public static T As<T>(this object obj) where T : class { return obj as T; } } 
+1
source

Source: https://habr.com/ru/post/1241711/


All Articles