VB.NET Indexers | Trickcode

VB.NET Indexers | Trickcode,Arrays,Indexers,indexer
Share it:
VB.NET Indexers | Trickcode



Introduction

I n this tutorial, we look at what indexes are and how we define them in VB.NET.


Arrays


If you have used arrays before then indexers should not be a big surprise. To understand indexers, let's look at an array as an example.

Let's assume you have defined the following WeekDays class. The days of the week are initialized in the constructor and you use the GetDayByNumber method to retrieve a certain day of the week. Note that the dayNumber parameter of the GetDayByNumber method is from 0 to 6 instead of e.g. from 1 to 7 in which case we must subtract one from dayNumber (like this Return _weekDays(dayNumber - 1)) before using it

Arrays



Public Class WeekDays

    Private _weekDays(7) As String

    Public Sub New()
        _weekDays(0) = "Monday"
        _weekDays(1) = "Tuesday"
        _weekDays(2) = "Wednesday"
        _weekDays(3) = "Thursday"
        _weekDays(4) = "Friday"
        _weekDays(5) = "Saturday"
        _weekDays(6) = "Sunday"
    End Sub

    Public Function GetDayByNumber(ByVal dayNumber As Integer) As String
        Return _weekDays(dayNumber)
    End Function

End Class

WeekDay's class works fine and we can use it in the following manner.


Dim wk As New WeekDays
        Console.WriteLine(wk.GetDayByNumber(3))

The output of the above code is Thursday.


Indexers


Now let's see how we can define an indexer in the WeekDay's class and what a change we experience. Ponder upon the following definition of the WeekDay's class that defines an indexer called WeekDay. An indexer is defined using the Default keyword - the rest looks very much like a normal property.



Public Class WeekDays

    Private _weekDays(7) As String

    Public Sub New()
        _weekDays(0) = "Monday"
        _weekDays(1) = "Tuesday"
        _weekDays(2) = "Wednesday"
        _weekDays(3) = "Thursday"
        _weekDays(4) = "Friday"
        _weekDays(5) = "Saturday"
        _weekDays(6) = "Sunday"
    End Sub
 
    Default Public Property WeekDay(ByVal dayNumber As Integer) As String
        Get
            Return _weekDays(dayNumber)
        End Get
        Set(ByVal value As String)
            _weekDays(dayNumber) = value
        End Set
    End Property

End Class
 
We use the indexer in the following manner. As you can see, the indexer has essentially turned the WeekDays class into an array. We index the wk object directly!


 Dim wk As New WeekDays
        Console.WriteLine(wk(3)) 'The output is Thursday
        
        wk(3) = "Thursday - Modified!" 'We modify the slot at index 3
An indexer is just like a method concerning indexer parameters and returns types. The return type can be any valid type. An indexer must at least have one parameter or the compiler throws an error at you.





                                      Share this article with your friends
Share it:

VB.NET

Post A Comment:

0 comments: