Skip to Content
Programming Visual Basic .NET, Second Edition
book

Programming Visual Basic .NET, Second Edition

by Jesse Liberty
April 2003
Intermediate to advanced
560 pages
14h 4m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET, Second Edition

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET

Programming Visual Basic .NET

Dave Grundgeiger
VB.NET Language in a Nutshell, Second Edition

VB.NET Language in a Nutshell, Second Edition

Steven Roman PhD, Ron Petrusha, Paul Lomax

Publisher Resources

ISBN: 0596004389Supplemental ContentCatalog PageErrata