MSDN Documentation

Microsoft Developer Network

Classes in VB.NET

Classes are the fundamental building blocks of object-oriented programming (OOP) in VB.NET. They serve as blueprints for creating objects, encapsulating data (fields or members) and behavior (methods or procedures) that operate on that data.

What is a Class?

A class defines the structure and behavior for a type of object. When you create an object from a class, it's called an instance of that class. Each instance has its own copy of the data defined by the class.

Declaring a Class

You declare a class using the Class keyword. The basic syntax is as follows:

Syntax Example


Public Class ClassName
    ' Member variables (fields)
    Private memberVariable As DataType

    ' Constructor (optional)
    Public Sub New(parameters As DataType)
        ' Initialize member variables
        memberVariable = parameters
    End Sub

    ' Methods (procedures)
    Public Sub MethodName(parameters As DataType)
        ' Code to execute
    End Sub

    ' Properties
    Public Property MyProperty As DataType
        Get
            Return memberVariable
        End Get
        Set(value As DataType)
            memberVariable = value
        End Set
    End Property
End Class
                

Class Members

Classes can contain various members:

Access Modifiers

Access modifiers control the visibility and accessibility of class members:

Creating Objects (Instantiating a Class)

To create an object from a class, you use the New keyword:

Object Instantiation


' Assuming 'MyClass' is a class defined elsewhere
Dim myObject As New MyClass()

' If the constructor takes arguments
Dim anotherObject As New MyClass("initial value")
                

Accessing Members

You use the dot (.) operator to access the members (fields, methods, properties) of an object:

Accessing Members Example


' Assuming myObject has a public property named 'Name' and a public method 'Greet'
myObject.Name = "Alice"
myObject.Greet()
                
Note: Understanding classes is crucial for mastering object-oriented programming in VB.NET. They allow for code reusability, modularity, and easier maintenance.

Example: A Simple `Car` Class

Car Class Definition


Public Class Car
    ' Fields
    Private _make As String
    Private _model As String
    Private _year As Integer
    Private _isRunning As Boolean = False

    ' Constructor
    Public Sub New(make As String, model As String, year As Integer)
        _make = make
        _model = model
        _year = year
    End Sub

    ' Properties
    Public Property Make As String
        Get
            Return _make
        End Get
        Set(value As String)
            _make = value
        End Set
    End Property

    Public ReadOnly Property Model As String ' Read-only property
        Get
            Return _model
        End Get
    End Property

    Public Property Year As Integer
        Get
            Return _year
        End Get
        Set(value As Integer)
            If value >= 1886 AndAlso value <= DateTime.Now.Year + 1 Then ' Basic validation
                _year = value
            Else
                Throw New ArgumentOutOfRangeException("Year", "Invalid year provided.")
            End If
        End Set
    End Property

    ' Methods
    Public Sub StartEngine()
        If Not _isRunning Then
            _isRunning = True
            Console.WriteLine("The car's engine has started.")
        Else
            Console.WriteLine("The car's engine is already running.")
        End If
    End Sub

    Public Sub StopEngine()
        If _isRunning Then
            _isRunning = False
            Console.WriteLine("The car's engine has stopped.")
        Else
            Console.WriteLine("The car's engine is already stopped.")
        End If
    End Sub

    Public Sub DisplayInfo()
        Console.WriteLine($"Car: {_year} {_make} {_model}. Engine running: {_isRunning}")
    End Sub
End Class
                

Using the Car Class


' Create instances of the Car class
Dim myCar As New Car("Toyota", "Camry", 2022)
Dim anotherCar As Car = New Car("Honda", "Civic", 2023)

' Access and modify properties
myCar.Year = 2023
' anotherCar.Model = "Accord" ' This would cause a compile error as Model is ReadOnly

' Call methods
myCar.StartEngine()
myCar.DisplayInfo()
anotherCar.StartEngine()
anotherCar.StopEngine()
anotherCar.DisplayInfo()

' Accessing read-only property
Console.WriteLine($"The model of the first car is: {myCar.Model}")
                
Tip: Always aim to encapsulate your data by making fields private and providing public properties to control access. This promotes better design and prevents accidental modification of data.