is and as…


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">A dev at Microsoft working on a
large managed code base just suggested this guideline… Our perf team buys it as
well.. />


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">is style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana"> should only be used when it’s
only necessary to test the type of some object. If you’re going to use the
object if the is condition succeeds, use as instead. This prevents
two cast operations which can be expensive. For
instance:

         
Good:


 


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">         
Foo foo = obj as Foo;  //only
cast
          if (foo !=
null)


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">         
{


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">                   
// use Foo


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">         
}

         
Bad:


 


style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">         
if (obj is Foo)  // cast
1
         
{
                   
Foo foo = (Foo)obj; //cast
2
                   
// use foo…
         
}


 

Comments (6)

  1. Blake says:

    Hmm… this wasn’t already in the guidelines/docs? I thought it was obvious.

  2. Chris Sells says:

    Don has this in his book, Essential .NET.

  3. Mujtaba Syed says:

    This tip is also found in Jeffrey’s book – page 120.

  4. How about you guys upgrading your optimizers so that both code sections produce the same IL? The "bad" version you have has the advantage of the variable "foo" bing in smaller scope.

  5. Sergio Pereira says:

    Can somebody put a new VB.NET operator that does the C#’s "as" ? That would be useful.

  6. Andrew Fung says:

    While I see the performance advantage, is it not a disadvantage that it masks potential developer errors by treating the case of lack of assignment (e.g. uninitialized state, which is fine) and incorrect assignment (e.g. unexpected sub-type being assigned) as the same?