Count
End Get
End Property
Default Public ReadOnly Property Item(ByVal Index As Integer) As GeometricShape
Get
Return CType(Shapes(Index), GeometricShape)
End Get
End Property
Public Sub Add(ByVal Shape As GeometricShape)
Shapes.Add(Shape)
End Sub
End Class
Public Class EntryPoint
Shared Sub Main()
Dim Rectangle As Rectangle = New Rectangle()
Dim Circle As Circle = New Circle()
Dim Drawing As Drawing = New Drawing()
Dim i As Integer = 0
Drawing.Add(Rectangle)
Drawing.Add(Circle)
For i = 0 To Drawing.Count - 1 Step 1
Dim Shape As GeometricShape = Drawing(i)
Shape.Draw()
Next
End Sub
End Class
CHAPTER 3 n CLASSES AND STRUCTURES 47
As shown, you can access the elements of the Drawing object in the Main() routine as if
they were inside a normal array. Also, since this indexer only has a Get accessor, it is read-only.
Keep in mind that if the collection holds onto references to objects, the client code can still
change the state of the contained object through that reference. But since the indexer is readonly,
the client code cannot swap out the object reference at a specific index with a reference
to a completely different object.
One difference is worth noting between a real array and the indexer. You cannot pass the
results of calling an indexer on an object as a ByRef parameter to a method as you can do with
a real array.
Pages:
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105