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?
Firstly look at the Jon Skeet answer for general question about casting in C#:
Don’t do this:
<code>if (randomObject is TargetType){TargetType foo = (TargetType) randomObject;// Do something with foo}</code><code>if (randomObject is TargetType) { TargetType foo = (TargetType) randomObject; // Do something with foo } </code>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:
<code>TargetType convertedRandomObject = randomObject as TargetType;if (convertedRandomObject != null){// Do stuff with convertedRandomObject}</code><code>TargetType convertedRandomObject = randomObject as TargetType; if (convertedRandomObject != null) { // Do stuff with convertedRandomObject } </code>TargetType convertedRandomObject = randomObject as TargetType; if (convertedRandomObject != null) { // Do stuff with convertedRandomObject }
Then see similar topics:
- What is the difference between the following casts in c#?
- Casting vs using the ‘as’ keyword in the CLR
- What is a difference between casts: (A) x and x as A?
1