Searchable Indexer : Indexer « Class Module « VB.Net Tutorial






Option Strict On
 Imports System

 Public Class MyArray
     Private strings(255) As String
     Private ctr As Integer = 0

     Public Sub New(ByVal ParamArray initialStrings() As String)
         Dim s As String
         For Each s In initialStrings
             strings(ctr) = s
             ctr += 1
         Next
     End Sub
     Public Sub Add(ByVal theString As String)
         If ctr >= strings.Length Then
         Else
             strings(ctr) = theString
             ctr += 1
         End If
     End Sub

     Default Public Property Item( _
        ByVal index As Integer) As String
         Get
             If index < 0 Or index >= strings.Length Then
             Else
                 Return strings(index)
             End If
         End Get
         Set(ByVal Value As String)
             If index >= ctr Then
             Else
                 strings(index) = Value
             End If
         End Set
     End Property

     Default Public Property Item( _
        ByVal index As String) As String
         Get
             If index.Length = 0 Then
             Else
                 Return strings(findString(index))
             End If
         End Get
         Set(ByVal Value As String)
             strings(findString(index)) = Value
         End Set
     End Property

     Private Function findString( _
        ByVal searchString As String) As Integer
         Dim i As Integer
         For i = 0 To strings.Length - 1
             If strings(i).StartsWith(searchString) Then
                 Return i
             End If
         Next
         Return -1
     End Function

     Public Function Count() As Integer
         Return ctr
     End Function
 End Class

 Public Class Tester

     Public Sub Run()
     End Sub

     Public Shared Sub Main()
         Dim lbt As New MyArray("Hello", "World")
         Dim i As Integer

         Console.WriteLine("After creation...")
         For i = 0 To lbt.Count - 1
             Console.WriteLine("lbt({0}): {1}", i, lbt(i))
         Next

         ' add a few strings
         lbt.Add("W")
         lbt.Add("s")
         lbt.Add("n")
         lbt.Add("t")

         Console.WriteLine(vbCrLf & "After adding strings...")
         For i = 0 To lbt.Count - 1
             Console.WriteLine("lbt({0}): {1}", i, lbt(i))
         Next

         Dim subst As String = "e"
         lbt(1) = subst
         lbt("H") = "GoodBye"

         Console.WriteLine(vbCrLf & "After editing strings...")
         For i = 0 To lbt.Count - 1
             Console.WriteLine("lbt({0}): {1}", i, lbt(i))
         Next
     End Sub
 End Class
After creation...
lbt(0): Hello
lbt(1): World

After adding strings...
lbt(0): Hello
lbt(1): World
lbt(2): W
lbt(3): s
lbt(4): n
lbt(5): t

After editing strings...
lbt(0): GoodBye
lbt(1): e
lbt(2): W
lbt(3): s
lbt(4): n
lbt(5): t








6.27.Indexer
6.27.1.Define Indexer for your own class
6.27.2.Searchable Indexer