Section 13.3. Casting to an Interface


13.3. 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. You can create a reference of type IStorable , and assign that to each member in the array, accessing the IStorable methods and property (but not the Document -specific methods, because all the compiler knows is that you have an IStorable , not a Document ).

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 property Status , but not to the Document 's private member variable status , even though the IStorable reference was instantiated as a reference to the Document . The IStorable reference only knows about the IStorable interface, not about the Document 's internal members.

Thus far, you have assigned the Document object (myDoc) to an IStorable reference.



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net