Home >>VB.Net Built-in Functions >VB.Net program to create an array of objects of the class

VB.Net program to create an array of objects of the class

Wite a VB.Net program to create an array of objects of the class

Here, we create a Sample Class and then create a Sample Class object array, and then use objects to call the class methods.

Program :

Below is the source code for creating an array of objects for the class. The program given is compiled and successfully executed.

'VB.Net program to create an array of objects of the class.


Class Sample
    Private num1 As Integer
    Private num2 As Integer
    Public Sub SetValues(ByVal n1 As Integer, ByVal n2 As Integer)
        num1 = n1
        num2 = n2
    End Sub
    Public Sub PrintValues()
        Console.WriteLine("Num1: " & num1)
        Console.WriteLine("Num2: " & num2)
    End Sub
End Class
Module Module1
    Sub Main()
        Dim obj(2) As Sample
        obj(0) = New Sample()
        obj(1) = New Sample()
        Console.WriteLine("Object(0) data:")
        obj(0).SetValues(20, 30)
        obj(0).PrintValues()
        Console.WriteLine(vbCrLf & "Object(1) data:")
        obj(1).SetValues(40, 50)
        obj(1).PrintValues()
    End Sub
End Module
	
Output:
Object1 data:
Num1: 20
Num2: 30
Object2 data:
Num1: 40
Num2: 50
Explanation:

We created a Module1 module in the program above. Here, we created a sample class that includes two num1 and num2 integer data members. We have developed two SetValues() and PrintValues() methods here ().

We created an object list of the Sample class in the Main() method. Using an array subscript operator to set and print the value of the data members, then call methods.