Reputation: 549
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.
Upvotes: 3
Views: 90
Reputation: 4091
If you are before C#7, otherwise use Selman's answer.
x => (x as View)?.IsTemplate ?? false;
Upvotes: 4
Reputation: 101681
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
Upvotes: 6