Consuming Interfaces

 <  Day Day Up  >  

When a type implements an interface, instances of that type can be converted to the interface type. This allows all types that implement the interface to be treated in the same way. For example, the following code takes an instance of a type that implements the ISizeable interface and prints its size .

 Module Test   Sub PrintSize(ByVal Shape As ISizeable)     Console.WriteLine(Shape.Width & "," & Shape.Height)   End Sub   Sub Main()     Dim s As Square = New Square()     Dim r As Rectangle = New Rectangle()     PrintSize(s)     PrintSize(r)   End Sub End Module 

Both an instance of Square and an instance of Rectangle can be passed to the PrintSize method because both types implement the ISizeable interface.

As noted in the previous section, a type can implement an interface with different names than the ones the interface uses. If the Square class implements the Width and Height properties with properties named SquareWidth and SquareHeight (see the previous section for an example of this), the names used to access the property depend on whether the instance is being accessed as a class or as an interface. For example:

 Module Test   Sub PrintSize(ByVal Shape As ISizeable)     Console.WriteLine(Shape.Width & "," & Shape.Height)   End Sub   Sub PrintSquareSize(ByVal Square As Square)     Console.WriteLine(Square.SquareWidth & "," & Square.SquareHeight)   End Sub   Sub Main()     Dim s As Square = New Square()     PrintSize(s)     PrintSquareSize(s)   End Sub End Module 

In this example, the PrintSize method does not have to change, because it deals with the interface ISizeable , whose property names are Width and Height . But because the PrintSquareSize method deals with an instance of Square , it has to use the property names as they are defined in Square ”that is, SquareWidth and SquareHeight .

The conversion from a type to an interface it implements is widening because the conversion can never fail. The conversion from an interface to a type that implements it is narrowing because an interface can be implemented by many different types. For example, converting from ISizeable to Square may fail because the ISizeable instance may really be an instance of Rectangle (which cannot be converted to Square ).

Interoperability

Because COM classes do not always declare every interface that they support, it is valid to convert a class to an interface that it does not explicitly implement, and vice versa. If the class is a COM class, this turns into a runtime QueryInterface call for the particular interface. If the class is not a COM class, the conversion will fail at runtime.


 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

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