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, as if they were members of the Document class:

Dim doc As New Document("Test Document")
doc.Status = -1
doc.Read( )

Alternatively, you can create an instance of the interface, and then use that interface to access the methods of that interface:

Dim isDoc As IStorable = doc
isDoc.status = 0
isDoc.Read( )

In Chapter 9, you’ll see that at times you may create collections of objects that implement a given interface (e.g., a collection of storable objects). You can manipulate them without knowing their real type—so long as they implement IStorable. For instance, you won’t know that you have a Document object; rather, you’ll know only that the object in question implements 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.”

As stated earlier, you cannot instantiate an interface directly—that is, you cannot write:

IStorable isDoc As New IStorable( )

You can, however, create an instance of the implementing class, ...

Get Programming Visual Basic .NET, Second Edition 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.