Welcome to Geekdojo Sign in | Join | Help

as and is

I read the following from Brad Adams' blog sometime back, I didn't need it then but kind of kept it in mind. Today I needed this one and I actually used it :-). So, hopefully I'll remember it from now on. Yet another 'key of C#' lesson for me.

“is 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:

          Foo foo = obj as Foo;  //only cast
          if (foo != null)
{

                   // use Foo

          }

Bad:

          if (obj is Foo)  // cast 1  {
                    Foo foo = (Foo)obj; //cast 2
                    // use foo…
          }

Published Saturday, November 08, 2003 11:27 AM by richardhsu
Filed Under:

Comments

Anonymous comments are disabled