Monday, June 20, 2005

 

Run Type Identification - as operator

If you want to cast an object to another type, but don’t want exceptions to be raised if the cast fails, the as operator is the choice:

expr as type

If the cast succeed: expr will be cast to type type.
If the cast fails: expr will have a null reference.

Here’s an example:
using System;

class A { }
class B : A { }

class CheckCast
{
public static void Main()
{
A a = new A();
B b = new B();

// replace this with
/*
if (a is B)
b = (B)a;
else
b = null;
*/
b = a as B;

if (b == null)
Console.WriteLine("Cast b = (B) a is not allowed.");
else
Console.WriteLine("Cast b = (B) a is allowed.");
}
}

(Taken from the C#: The Complete Reference by Schildt).

The cast will fail, since a is not a B;
Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?