13

When I write code like this, where obj is a local variable:

if (obj is IMyInterface)
{
   var result = (IMyInterface)obj;
   // ....
}

Resharper offers to change it into code like this:

var result = obj as IMyInterface;
if (result != null)
{
   // ...
}

I prefer the former, as it offers no opportunity for accidental null reference exceptions. What reasons are there for preferring the other form?

Why does Resharper recommend this?

1 Answer 1

25

Firstly look at the Jon Skeet answer for general question about casting in C#:

Don't do this:

if (randomObject is TargetType)
{
    TargetType foo = (TargetType) randomObject;
    // Do something with foo
}

Not only is this checking twice, but it may be checking different things, if randomObject is a field rather than a local variable. It's possible for the "if" to pass but then the cast to fail, if another thread changes the value of randomObject between the two.

(...)

If randomObject might be an instance of TargetType and TargetType is a reference type, then use code like this:

TargetType convertedRandomObject = randomObject as TargetType;
if (convertedRandomObject != null)
{
    // Do stuff with convertedRandomObject
}

Then see similar topics:

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.