Accessing an interface on an object

Using the is operator to work with an interface requires your code to access an object twice:

• Once to query the object to see whether it implements an interface

• Once to access the object's interface implementation using the casting operator

You can combine these two accesses by using the as operator. The as operator performs both activities in a single statement. Listing 13-2 is a modified version of Listing 13-1 that uses the as statement instead of the is statement:

Listing 13-2: Using the as Keyword to Work with an Interface using System;

public interface IPrintMessage {

class Classl {

public void Print() {

Console.WriteLine("Hello from Classl!");

class Class2 : IPrintMessage {

public void Print() {

Console.WriteLine("Hello from Class2!");

class MainClass {

public static void Main() {

PrintClass PrintObject = new PrintClass(); PrintObject.PrintMessages();

class PrintClass {

public void PrintMessages() {

Classl Objectl = new Class1();

Class2 Object2 = new Class2();

PrintMessageFromObject(Objectl); PrintMessageFromObject(Object2);

private void PrintMessageFromObject(object obj)

IPrintMessage PrintMessage;

PrintMessage = obj as IPrintMessage; if(PrintMessage != null) PrintMessage.Print();

The as operator is used as a part of an expression constructed as follows:

An object identifier The keyword as An interface identifier

If the object named in the expression implements the interface named in the expression, the object's implementation of the interface is returned as the result of the expression. If the object named in the expression does not implement the interface named in the expression, the result of the expression is assigned an empty value represented by the C# keyword null.

The new implementation of the private PrintMessageFromObject() method uses the as operator. It declares a local variable of the IPrintMessage interface type and uses the as operator to access the object's implementation of the method.

After the as operation completes, the interface implementation variable is checked to see whether it has the value null. If the variable is not equal to null, the supplied object is known to implement the interface, and the interface's method can be called.

Listing 13-2 is functionally equivalent to Listing 13-1, and Listing 13-2 writes the following text out to the console:

Hello from Class2!

0 0

Post a comment