Information Technology Reference
In-Depth Information
Using the as Operator with Interfaces
The as operator will be covered in detail in Chapter 18, but I will mention it here as well, since
it is commonly used with interfaces.
You saw earlier that you can cast a class object reference to a reference to an interface that
it implements. If, however, you attempt the cast on a class object that does not implement the
interface, the cast operation will raise an exception. You can avoid this problem by using the as
operator instead. It works as follows:
￿
If the class implements the interface, the expression returns a reference to the interface.
If the class does not implement the interface, the expression returns null rather than
raising an exception.
￿
The following code shows the use of the as operator. The first line uses the as operator to
obtain an interface reference from a class object. The result of the expression sets the value of
b either to null or to a reference to an ILiveBirth interface.
The second line checks the value of b , and if it is not null , executes the command that calls
the interface member method.
Class object ref Interface name
ILiveBirth b = a as ILiveBirth; // Similar to cast: (ILiveBirth)a
Interface ref Operator
if (b != null)
Console.WriteLine("Baby is called: {0}", b.BabyCalled());
Search WWH ::




Custom Search