VB.Net program to demonstrate the indexer

Here, we are going to demonstrate the indexer in VB.Net.
Submitted by Nidhi, on January 02, 2021 [Last updated : March 06, 2023]

Implement indexer in VB.Net

Here, we will create a class and implement an indexer to set and get the value of arrays defined inside the class.

Program/Source Code:

The source code to demonstrate the indexer is given below. The given program is compiled and executed successfully.

VB.Net code to implement the indexer

'VB.net program to demonstrate the indexer.

Class Student
    Dim Id(5) As Integer
    Dim Name(5) As String

    Public Property StudentID(ByVal index As Integer) As Integer
        Get
            Return Id(index)
        End Get
        Set(value As Integer)
            Id(index) = value
        End Set

    End Property

    Public Property StudentName(ByVal index As Integer) As String
        Get
            Return Name(index)
        End Get
        Set(value As String)
            Name(index) = value
        End Set
    End Property
End Class

Module Module1
    Sub Main()
        Dim Stu As New Student

        Stu.StudentID(0) = 101
        Stu.StudentName(0) = "Rohit Kohli"

        Stu.StudentID(1) = 102
        Stu.StudentName(1) = "Virat Sharma"

        Console.WriteLine("Student Information: ")
        Console.WriteLine(vbTab & "ID      : {0}", Stu.StudentID(0))
        Console.WriteLine(vbTab & "Name    : {0}", Stu.StudentName(0))
        Console.WriteLine(vbTab & "ID      : {0}", Stu.StudentID(1))
        Console.WriteLine(vbTab & "Name    : {0}", Stu.StudentName(1))
    End Sub
End Module

Output:

Student Information:
        ID      : 101
        Name    : Rohit Kohli
        ID      : 102
        Name    : Virat Sharma

Explanation:

In the above program, we created a class Student class that contains two data members Id, Name. The Id and Name data members are arrays that can store 5 values. Here, we implemented indexer StudentId and StudentName to set and get values of data members using the index.

After that, we created a module Module1 that contains the Main() method, the Main() method is the entry point for the program. And, we created an object of the Student class and then set the values of data members using Indexer and then print the student information on the console screen.

VB.Net Basic Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.