Jeff Adkins' WebLog

Sr. Software Design Engineer, Microsoft

CSharpBits:The is and as Operators

CSharp Bits is a tutorial-based digest that explains the C# programming language. It evolves, covering prerequisite topics and is currently broad in coverage rather than getting deep into a specific topic. That will come after a basis has been established.  I issue the topics daily (:p), and mainly cover one topic in each issue, so readers can fit it in their daily routine.  I email these topics internally at Microsoft and have been asked to blog the digests externally to reach out to the user community.

 All code examples are meant to demonstrate the topic only. It is neither shippable nor secure code by any stretch of the imagination.  An archive of the topics I submitted internally within Microsoft before I started blogging these out is not currently available externally.

==================================================================================================

The is Operator

You can handle incompatible types by catching InvalidCastException, but there are other ways of handling this problem, such as the is operator. The is operator allows you to determine whether an object reference can be converted into a reference to a given class.

You can use the is operator to test the type of the object without performing a conversion. The is operator returns true if the value on the left is not null and a cast to the class on the right, if performed, would complete without throwing an exception. Otherwise, is returns false.

if (a is Bird)
  
b = (Bird) a; // Safe, because "a is Bird" returns true
else
  
Console.WriteLine("Not a Bird");

You can think of the relationship between inherited classes as an "is a kind of" relationship, as in "A bird is a kind of animal." References in the variable a must be references to Animal objects, and b is a kind of animal. Of course, b is a bird as well, but a bird is just a special case of an animal. The converse is not true. An animal is not a type of bird. Some animals are birds, but it is not true that all animals are birds.

So the following expression can be read as "If a is a kind of bird," or "If a is a bird or a type derived from bird."

if (a is Bird)

 The as Operator

You can use the as operator to perform conversions between types without raising an exception.

The following statement performs a conversion of the reference in a to a value that references a class of type Bird, and the runtime automatically checks to ensure that the conversion is acceptable.

b = a as Bird;

Error Handling

The as operator differs from the cast operator in the way it handles errors. If, in the preceding example, the reference in variable a cannot be converted in a reference to an object of class Bird, the value null is stored in b, and the program continues. The as operator never raises an exception.

You can rewrite the previous code as follows to display an error message if the conversion cannot be performed:

Bird b = a as Bird;
if (b == null)
  
Console.WriteLine("Not a bird");

Although as never raises an exception, any attempt to access through the converted value will raise a NullReferenceException if it is null. Therefore, you should always check the return value from as.

Published Tuesday, March 16, 2004 11:34 AM by Jeff Adkins
Filed under:

Comments

 

Jerry Pisk said:

Why exactly does "is" return false when the object is null? Did the C# specification change and null is no longer a valid object value?
March 16, 2004 1:26 PM
 

Ron said:

Jeff,

As always, thanks for these articles.

1) how does the "is" operator check that the type of object is the same?

2) Why do we need a cast operator? Is it not better to always use the "as" operator (and check for null)?
March 16, 2004 4:21 PM
 

Jeff Adkins said:

1)I'm not certain, but I assume it's doing a typeOf call or a reflection runtime GetType() call. Here's a reference..
http://msdn.microsoft.com/library/en-us/csref/html/vclrftypeofpg.asp?frame=true

2)The cast will raise the InvalidCastException for you to catch and you have to handle your own exception handling with the "as" operator. Otherwise, you're making a good point when it comes to reference types. Casting is used more for value types.

March 16, 2004 5:49 PM
 

Jeff Adkins said:

The "is" Operator is trying to determine if a cast can be made without error. If the object reference is null, that means it is not pointing to a current object in memory and an error would be raised when the framework tries to perform a typeOf operator or a GetType() call on a null value. Also, I believe a cast on reference variable with a current null value would raise an exception. These are my assumptions. If you're still curious, try testing these two scenarios. See if you can do a GetType or use the typeOf operator on a ref variable with a null value. And, separtely, try to do a cast on this variable with a null value.

March 16, 2004 6:13 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker