Article ID: 168830
Article Last Modified on 6/29/2004
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.
Function IShape(oShape As IShape) As IShape
Set IShape = oShape
End Function
You 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 With
You 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.
Type Name --------------------------- Class Module IShape Class Module ICircle Class Module ISquare Form Form1
Option Explicit
Public Sub SetXY(ByVal NewX As Long, ByVal NewY As Long)
End Sub
Public Sub Draw(oDrawSpace As Object)
End Sub
Option Explicit
Implements IShape
Dim X As Long, Y As Long, iRadius As Long
Private Sub IShape_Draw(oDrawSpace As Object)
oDrawSpace.Circle (X, Y), iRadius
End Sub
Private Sub IShape_SetXY(ByVal NewX As Long, ByVal NewY As Long)
X = NewX
Y = NewY
End Sub
Public Property Let Radius(ByVal NewVal As Long)
iRadius = NewVal
End Property
Option Explicit
Implements IShape
Dim X As Long, Y As Long, Side As Long
Private Sub IShape_Draw(oDrawSpace As Object)
oDrawSpace.Line (X, Y)-(X + Side, Y + Side), , B
End Sub
Private Sub IShape_SetXY(ByVal NewX As Long, ByVal NewY As Long)
X = NewX
Y = NewY
End Sub
Public Property Let SideLength(ByVal NewVal As Long)
Side = NewVal
End Property
Option Explicit
Private Sub Command1_Click()
Dim C As ICircle, S As ISquare
Set C = New ICircle
Set S = New ISquare
' Manipulate circle shape (using With)
C.Radius = 250
With IShape(C)
.SetXY 400, 400
.Draw Me
End With
' Manipulate square shape (without using With)
IShape(S).SetXY 700, 300
S.SideLength = 300
IShape(S).Draw Me
End Sub
Function IShape(oShape As IShape) As IShape
Set IShape = oShape
End Function
Additional query words: kbVBp500 kbVBp600 kbdse kbDSupport kbVBp
Keywords: kbhowto KB168830