O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Casting to an Interface

You can access the members (i.e., methods and properties) of an interface through the object of any class that implements the interface. Thus, you can access the methods and properties of IStorable, through the Document object:

Document doc = new Document("Test Document");
doc.status = -1;
doc.Read();

In Chapter 16, you’ll learn that at times you won’t know that you have a Document object; rather you’ll know only that you have objects that implement IStorable. You can create a variable of type IStorable and cast your Document to that type. You can then access the IStorable methods through the IStorable variable.

When you cast you say to the compiler, “trust me, I know this object is really of this type.” In this case you are saying “trust me, I know this document really implements IStorable, so you can treat it as an IStorable.”

Casting is safe to do because the Document object implements IStorable and thus is safely treated as an IStorable object. You cast by placing the type you are casting to in parentheses. The following line declares a variable of type IStorable and assigns to that variable the Document object, cast to type IStorable:

IStorable isDoc = (IStorable) doc;

You can read this line as “cast doc to IStorable and assign the resulting IStorable object to the variable isDoc, which is declared to be of type IStorable.” Note that the variable isDoc is now a reference to the same document, but that reference is of type IStorable and so has the methods ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required