Reputation: 35194
I just declared a variable like this:
bool b = (x is Foo) ? (x as Foo).Bar == 1 ? false;
But resharper told me that I could simplify the expression, so I rewrote it like this:
bool b = (x as Foo).Bar == 1;
Amd now resharper is satisfied, but is "exception safe"? For example, will it return false if x
isnt of the type Foo
?
Upvotes: 0
Views: 317
Reputation: 23324
I think Resharper is complaining, because the first version casts twice. This will only cast once:
Foo xAsFoo = x as Foo;
bool b = (xAsFoo != null) ? xAsFoo.Bar == 1 : false;
Or shorter:
Foo xAsFoo = x as Foo;
bool b = (xAsFoo != null) && xAsFoo.Bar == 1;
Upvotes: 2
Reputation: 62246
Don't know why Resharper tell this, but it wrong.
As in the case, when x
is not Foo, it will raise an exception.
bool b = (x as Foo).Bar == 1; //IF X IS SOMETHING ELSE, EXCEPTION !
as the as operator allow to run cast, but in case of the failure, returns null
.
So x as Foo == null
, and accessing property of null
will raise an exception.
Upvotes: 0
Reputation: 17994
The second will throw a NullReferenceException
if x isn't of the type Foo
Upvotes: 4