Search This Blog

Thursday, March 27, 2014

Introduction To The is and as Operator in C#

The is and as Operator in C#

Sometimes, however, you may not know at compile time whether an object supports a particular interface.

The is operator lets us query whether an object implements an interface (or derives from a base class). The form of the is operator is:
if ( expression is type )
The is operator evaluates true if the expression (which must be a reference type, such as an instance of a class) can be safely cast to type without throwing an exception.
The as operator is similar to is, but it goes a step further. The as operator tries to cast the object to the type, and if an exception would be thrown, it instead returns null:
ICompressible myCompressible = myObject as ICompressible
if ( myCompressible != null )
The is operator is slightly less efficient than using as, so the as operator is slightly preferred over the is operator, except when you want to do the test but not actually do the cast (a rare situation).

No comments:

Post a Comment