Using as
Sometimes you will want to try a conversion at runtime, but not throw an exception if the
conversion fails (which is the case when a cast is used). To do this, use the as operator,
which has this general form:
expr as type
Here, expr is the expression being converted to type. If the conversion succeeds, then a
reference to type is returned. Otherwise, a null reference is returned. The as operator can
be used to perform only reference, boxing, unboxing, or identity conversions.
The as operator offers a streamlined alternative to is in some cases. For example,
consider the following program that uses is to prevent an invalid cast from occurring:
// Use is to avoid an invalid cast.
using System;
class A {}
class B : A {}
class CheckCast {
static void Main() {
A a = new A();
B b = new B();
// Check to see if a can be cast to B.
if(a is B) // if so, do the cast
b = (B) a;
else // if not, skip the cast
b = null;
if(b==null)
Console.WriteLine("The cast in b = (B) a is NOT allowed.");
else
Console.WriteLine("The cast in b = (B) a is allowed");
}
}
Sometimes you will want to try a conversion at runtime, but not throw an exception if the
conversion fails (which is the case when a cast is used). To do this, use the as operator,
which has this general form:
expr as type
Here, expr is the expression being converted to type. If the conversion succeeds, then a
reference to type is returned. Otherwise, a null reference is returned. The as operator can
be used to perform only reference, boxing, unboxing, or identity conversions.
The as operator offers a streamlined alternative to is in some cases. For example,
consider the following program that uses is to prevent an invalid cast from occurring:
// Use is to avoid an invalid cast.
using System;
class A {}
class B : A {}
class CheckCast {
static void Main() {
A a = new A();
B b = new B();
// Check to see if a can be cast to B.
if(a is B) // if so, do the cast
b = (B) a;
else // if not, skip the cast
b = null;
if(b==null)
Console.WriteLine("The cast in b = (B) a is NOT allowed.");
else
Console.WriteLine("The cast in b = (B) a is allowed");
}
}