0
if(someVar is MyClass)

Resharper suggeted to replace this with

var some = someVar as MyClass;
if(some!= null){ /*.......*/ }

Is there any performance advantage? I remember something related with boxing and unboxing variables, but not sure, if I'm on the right path. Or is Resharper just suggesting proper syntax?

Vectro
  • 135
  • 2
  • 9

1 Answers1

1

The reason it suggests this is probably because the former will require two casts:

if(someVar is MyClass) 
{
    var myVar = (MyClass) someVar;
}

The is operator does a cast behind the scenes and returns a boolean whether or not it is allowed.

If you use as though, you pretty much "cache" the result and you will only have one cast necessary.

var myVar = someVar as MyClass
if(myVar != null)
{
    // No cast needed
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170