c# - Elvis operator in a casting invocation chain -
the elvis operator, aka null-conditional operator, massively cool.
in linq queries works great in concert null-coalescing "??" operator.
somedata.where(dt=>(dt?.inner?.innermost?.include=="yes")??false);
but do if need cast intermediate values?
for 1 link in chain, works out fine.
somedata.where(dt=>( ((innerclass)dt?.inner) ?.innermost)?.include=="yes") ??false);
but additional necessary casts cast , invocation "driven apart".
somedata.where(dt=>( ((innermostclass) <=== cast ((innerclass)dt?.inner) ?.innermost)?.include=="yes")) <=== use ??false);
probably messed the parenthesis more once here, hope idea.
though "trainwreck" invocation chain code smell, there more expressive way of doing improve succinctness , clarity?
you can keep chaining , prevent parenthesis using simple extension method:
dt?.inner.as<innerclass>()?.innermost.as<innermostclass>()?.include == "yes"
with extension method defined this:
public static class objectextensions { public static t as<t>(this object obj) t : class { return obj t; } }
Comments
Post a Comment