Creating classes Object in Visual Basic

When creating an object, you need to specify the New keyword. For example, the following code snippet creates a firstCar object (that is, an instance of the Car class) and then stores a reference to the object in the firstCar variable:

Example<

Module Module1

    Public Class Car
        Private name As String
        Private price As Decimal
        Private gears As Integer
    End Class

    Sub Main()

        Dim firstCar As New Car()

        ' OR

        Dim secondCar As New Car()
        secondCar = New Car()

        Console.ReadLine()
    End Sub

End Module

If you omit the New keyword, you’ll declare the variable, but you won’t create the object.

Example

Module Module1

    Public Class Car
        Private name As String
        Private price As Decimal
        Private gears As Integer
    End Class

    Sub Main()

        Dim firstCar As Car ' HERE VARIABLE IS DECLARED

        Console.ReadLine()
    End Sub

End Module
Share

You may also like...