Example of a class indexing in use.
Dim x As String="ABCDEF" Console.Write(x(2))
See how it possible to access the 3rd character of the string with the use of x(3)
Have you wonder how to implement them?
In this sample class code I use and array of Integer but it could any type.
Public Class ExampleOfClassIndexer Inherits System.Collections.CollectionBase Private m_Item(19) As Integer ' The important overloaded property the lets us do Class Indexing. Default Public Overloads Property Item(ByVal Index As Int32) As Integer Get ' Make sure the Index is within the bounds of the collection / array If Index < 0 Or Index > (m_Item.Count - 1) Then Throw New IndexOutOfRangeException ' Return the item at the specified index. Return CType(m_Item(Index), Integer) End Get ' Much the same as above but this time setting value at the specified index. Set(ByVal value As Integer) If Index < 0 Or Index > (m_Item.Count - 1) Then Throw New IndexOutOfRangeException m_Item(Index) = value End Set End Property End Class
It can be extend into a higher number of dimensions.
For Example, Requires a lot more Bound Checks.
Public Class ExampleOf_2DClassIndexer
Inherits System.Collections.CollectionBase
Private m_Item(7, 7) As Integer
Default Public Overloads Property Item(ByVal RowIndex As Int32, ByVal ColIndex As Int32) As Integer
Get
If (RowIndex < 0) Or (RowIndex > UBound(m_Item,1)) Then Throw New IndexOutOfRangeException("RowIndex out of bounds")
If (ColIndex < 0) Or (ColIndex > UBound(m_Item,2)) Then Throw New IndexOutOfRangeException("ColIndex out of bounds")
Return CType(m_Item(RowIndex, ColIndex), Integer)
End Get
Set(ByVal value As Integer)
If (RowIndex < 0) Or (RowIndex > UBound(m_Item,1)) Then Throw New IndexOutOfRangeException("RowIndex out of bounds")
If (ColIndex < 0) Or (ColIndex > UBound(m_Item,2)) Then Throw New IndexOutOfRangeException("ColIndex out of bounds")
m_Item(RowIndex, ColIndex) = value
End Set
End Property
End Class
So now you'll be a Class Indexing Coding Ninja






MultiQuote



|