Casting to an Interface
You can access the members of an interface through an object of any class that implements the interface. For example, because Document
implements IStorable
, you can access the IStorable
methods and property through any Document
instance:
Document doc = new Document("Test Document"); doc.Status = -1; doc.Read( );
At times, though, you won’t know that you have a Document
object; you’ll only know that you have objects that implement IStorable
, for example, if you have an array of IStorable
objects, as we mentioned earlier. You can create a reference of type IStorable
, and assign that to each member in the array, accessing the IStorable
methods and property. You cannot, however, access the Document
-specific methods because all the compiler knows is that you have an IStorable
, not a Document
.
As we mentioned before, you cannot instantiate an interface directly; that is, you cannot write:
IStorable isDoc = new IStorable;
You can, however, create an instance of the implementing class and then assign that object to a reference to any of the interfaces it implements:
Document myDoc = new Document(…); IStorable myStorable = myDoc;
You can read this line as “assign the IStorable
-implementing object myDoc
to the IStorable
reference myStorable
.”
You are now free to use the IStorable
reference to access the IStorable
methods and properties of the document:
myStorable.Status = 0; myStorable.Read( );
Notice that the IStorable
reference myStorable
has access to the IStorable
automatic ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.