Shorten and simply conditional statement?

Viewed 54

I have this statement (which works):

x => x is View v && (x as View).IsTemplate

where the IsTemplate property only exists on the derived type View

I would like to shorten it to:

x => x is View v & v.IsTemplate

But I cant, I get the error "use of unassigned local variable". Eventhough intellisense gives me the IsTemplate property. Is this impossible, or did I miss something in the syntax? It looks much nicer and I cant see any logic issues with it.

2 Answers

It's because you are using & operator in the second code, the right side will be evaluated even though the left operand evaluates to false. You should change it to &&

x => x is View v && v.IsTemplate

If you are before C#7, otherwise use Selman's answer.

x => (x as View)?.IsTemplate ?? false;
Related