O'Reilly logo

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

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