Johan
Johan

Reputation: 35194

Simplifying shorthand if bool

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

Answers (3)

Henrik
Henrik

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

Tigran
Tigran

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

Rui Jarimba
Rui Jarimba

Reputation: 17994

The second will throw a NullReferenceException if x isn't of the type Foo

Upvotes: 4

Related Questions