HOWTO: Cast an Object to a Different InterfaceLast reviewed: May 22, 1997Article ID: Q168830 |
The information in this article applies to:
SUMMARYWhen using an object that has multiple interfaces, you may be faced with assigning it to multiple variables of different object types to get at relevant interfaces. This is made more difficult by having to keep track of the different variables and clean them up properly. This article gives code for a simple function to allow casting an object to a different interface without the need to create additional object variables or keep track of them.
MORE INFORMATIONThe sample code below illustrates a common problem when utilizing objects that have multiple interfaces:
Dim Shape As IShape, C As ICircle, S As ISquare Set C = New ICircle Set Shape = C Shape.SetXY 100, 100 C.Radius = 50 Shape.Draw Me Set C = Nothing Set S = New ISquare Set Shape = S ' Critical line Shape.SetXY 300, 200 S.Side = 50 Shape.Draw Me Set Shape = Nothing Set S = NothingIf you forget to set the Shape object to S on the "Critical line," you will still be manipulating the Circle object in subsequent code. In addition, it's difficult to tell you are using the Shape object to get at additional interfaces or what object it's currently set to. To clear up this problem, create global functions in your application to cast the variables to their alternate interfaces. The example above requires only one function to cast to the IShape interface:
Function IShape(oShape As IShape) As IShape Set IShape = oShape End FunctionYou can then reference this function to perform the casting:
IShape(C).SetXY 100, 100 C.Radius = 50 IShape(C).Draw MeOr more efficiently:
With IShape(C) .SetXY 100, 100 C.Radius = 50 .Draw Me End WithYou no longer have to define, set, or otherwise keep track of additional variables for casting purposes. Giving the function the same name as the interface helps with program clarity.
Step-by Step Example
REFERENCESMicrosoft Visual Basic Help topic "Implements Statement" |
Keywords : kbcode vb5all VBKBVBA kbhowto
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |