Skip to content
LumenaryAcademy
Practice 60 min

Classes, interfaces and events

Defining your own types with properties and constructors, inheritance and interfaces, structures, and the events that drive Windows applications.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Objects that look after themselves

A library system needs books that know whether they are on loan, refuse a loan period of ninety days, and describe themselves sensibly when printed. A transport app needs buses and electric scooters that can both quote a price per kilometre, while only the scooter can be charged. A home controller needs a thermostat that tells the rest of the program when the temperature changes. Each of these is a job for a class: a type that bundles data with the procedures that keep that data valid.

Visual Basic .NET is a fully object-oriented language with the same object model as C#: classes, single inheritance, interfaces, properties and events. Its keywords are longer and more descriptive (MustInherit rather than abstract, Overridable rather than virtual), which many people find easier to read. It also has a few features of its own, notably WithEvents and Handles for wiring up events, which is how millions of Windows Forms buttons have been connected to code. Because Visual Basic and C# share one object model, a Visual Basic class can inherit from a C# class and implement a C# interface, and the other way round, which is what makes gradual migration between the two languages possible.

DefinitionsH

Classes, properties and constructors

Definition— Class and object

A class is a blueprint declared with Class ... End Class; an object is an instance of it, created with New. A class can contain fields (variables), properties, methods (Subs and Functions), constructors (Sub New) and events. Members are Public, Private, Protected (this class and derived classes) or Friend (anywhere in the same assembly).

Definition— Property

A member that callers use like a variable (book.Author = "...") but which is implemented by a Get procedure and, unless it is ReadOnly, a Set procedure. An auto-implemented property, Public Property Author As String, needs no code: the compiler creates a hidden field.

vb
Option Strict On

Public Class LibraryBook
    ' A Shared member belongs to the class, not to any one book.
    Public Shared Property BooksCreated As Integer

    ' Auto-implemented properties.
    Public ReadOnly Property Title As String
    Public Property Author As String
    Public Property Borrower As String

    ' A full property with validation in its setter.
    Private _loanDays As Integer = 14
    Public Property LoanDays As Integer
        Get
            Return _loanDays
        End Get
        Set(value As Integer)
            If value < 1 OrElse value > 60 Then
                Throw New ArgumentOutOfRangeException(NameOf(value), "a loan lasts 1 to 60 days")
            End If
            _loanDays = value
        End Set
    End Property

    ' A computed, read-only property.
    Public ReadOnly Property IsOnLoan As Boolean
        Get
            Return Borrower IsNot Nothing
        End Get
    End Property

    ' The constructor is always called Sub New.
    Public Sub New(title As String)
        Me.Title = title
        BooksCreated += 1
    End Sub

    Public Function Lend(toWhom As String, today As Date) As Date
        If IsOnLoan Then Throw New InvalidOperationException($"{Title} is already on loan")
        Borrower = toWhom
        Return today.AddDays(LoanDays)
    End Function

    Public Overrides Function ToString() As String
        Return $"""{Title}"" by {Author}" & If(IsOnLoan, $" (on loan to {Borrower})", "")
    End Function
End Class

Module Program
    Sub Main()
        ' An object initializer sets properties right after the constructor runs.
        Dim book As New LibraryBook("Half of a Yellow Sun") With {.Author = "Chimamanda Ngozi Adichie"}
        Dim other As New LibraryBook("One Hundred Years of Solitude") With {.Author = "Gabriel García Márquez", .LoanDays = 21}

        Dim due = book.Lend("Kwame", #11/19/2026#)
        Console.WriteLine(book)
        Console.WriteLine($"due back {due:yyyy-MM-dd}")
        Console.WriteLine(other)
        Console.WriteLine($"{LibraryBook.BooksCreated} books created")

        Try
            other.LoanDays = 90
        Catch ex As ArgumentOutOfRangeException
            Console.WriteLine($"refused: {ex.Message}")
        End Try
    End Sub
End Module

It prints:

text
"Half of a Yellow Sun" by Chimamanda Ngozi Adichie (on loan to Kwame)
due back 2026-12-03
"One Hundred Years of Solitude" by Gabriel García Márquez
2 books created
refused: a loan lasts 1 to 60 days (Parameter 'value')
  • Auto-implemented properties (Public Property Author As String) cover simple data. A ReadOnly auto-property can be set only in the constructor, which is how Title is protected from change.
  • A full property has Get and Set blocks and usually a private backing field (_loanDays, by a common naming convention). The setter validates the value, so no code anywhere can give a book an impossible loan period; that rule is the class's invariant.
  • Sub New is the constructor. Me refers to the current object, and Me.Title = title distinguishes the property from the parameter. (Remember that names are not case-sensitive: title and Title are the same name, so Me. is needed here.)
  • Shared members belong to the class, not to each object, so LibraryBook.BooksCreated counts every book. (A Module is, in effect, a class whose members are all Shared.)
  • Overrides Function ToString() gives objects a readable description; Console.WriteLine(book) calls it.
  • Object initializers, New LibraryBook(...) With {.Author = "..."}, set properties right after construction. Note the leading dots.
  • NameOf(value) produces the parameter's name as a string, so an exception message stays correct if the parameter is renamed. Inside a string, two double quotes stand for one.
Worked examplesH

Inheritance and interfaces

Visual BasicC#Meaning
Inherits Vehicle: Vehiclederive from a base class
MustInherit Classabstract classcannot be instantiated; meant to be derived from
MustOverrideabstract memberno implementation here; derived classes must provide one
Overridablevirtualderived classes may replace it
Overridesoverridereplaces a base member
NotInheritable Classsealed classcannot be derived from
Shadowsnew modifierhides a base member instead of overriding it
MyBasebasethe base class's version of a member
Implements IChargeable: IChargeablepromise to provide an interface's members
vb
Option Strict On

Public Interface IChargeable
    ReadOnly Property BatteryPercent As Integer
    Sub Charge(minutes As Integer)
End Interface

' MustInherit: a base class that cannot be created on its own.
Public MustInherit Class Vehicle
    Public ReadOnly Property Name As String

    Protected Sub New(name As String)
        Me.Name = name
    End Sub

    ' MustOverride: every derived class must supply this.
    Public MustOverride Function CostPerKm() As Decimal

    ' Overridable: derived classes may replace this.
    Public Overridable Function Describe() As String
        Return $"{Name}: {CostPerKm():F2} per km"
    End Function
End Class

Public Class Bus
    Inherits Vehicle

    Public Sub New()
        MyBase.New("bus")
    End Sub

    Public Overrides Function CostPerKm() As Decimal
        Return 0.08D
    End Function
End Class

Public NotInheritable Class ElectricScooter
    Inherits Vehicle
    Implements IChargeable

    Private _battery As Integer = 40

    Public Sub New()
        MyBase.New("e-scooter")
    End Sub

    Public Overrides Function CostPerKm() As Decimal
        Return 0.15D
    End Function

    ' Implements maps a member to the interface member explicitly; the names may differ.
    Public ReadOnly Property Battery As Integer Implements IChargeable.BatteryPercent
        Get
            Return _battery
        End Get
    End Property

    Public Sub Charge(minutes As Integer) Implements IChargeable.Charge
        _battery = Math.Min(100, _battery + minutes \ 2)
    End Sub

    Public Overrides Function Describe() As String
        Return MyBase.Describe() & $", battery {_battery}%"
    End Function
End Class

Module Program
    Sub Main()
        Dim fleet As New List(Of Vehicle) From {New Bus(), New ElectricScooter()}
        For Each v In fleet
            Console.WriteLine(v.Describe())
        Next

        ' TypeOf ... Is tests the run-time type; TryCast converts or gives Nothing.
        For Each v In fleet
            Dim chargeable = TryCast(v, IChargeable)
            If chargeable IsNot Nothing Then
                chargeable.Charge(90)
                Console.WriteLine($"{v.Name} charged to {chargeable.BatteryPercent}%")
            End If
            Console.WriteLine($"{v.Name} is a Bus? {TypeOf v Is Bus}")
        Next
    End Sub
End Module

It prints:

text
bus: 0.08 per km
e-scooter: 0.15 per km, battery 40%
bus is a Bus? True
e-scooter charged to 85%
e-scooter is a Bus? False
  • Vehicle is MustInherit: there is no such thing as a plain vehicle, only buses and scooters. Its MustOverride function forces every kind of vehicle to state its cost, while Describe is Overridable, with a sensible default.
  • Polymorphism: the loop calls v.Describe() on each item of a List(Of Vehicle) (lists are the next lesson's subject), and each object runs its own version. ElectricScooter.Describe extends the base version through MyBase.Describe().
  • Constructors in derived classes call the base constructor with MyBase.New(...), which must be their first statement. The base constructor is Protected, so only derived classes can call it.
  • Interfaces declare members without implementations. Visual Basic requires an explicit Implements clause on each member that implements an interface member, naming exactly which member it fulfils: Public ReadOnly Property Battery As Integer Implements IChargeable.BatteryPercent. The class's name for the member (Battery) need not match the interface's (BatteryPercent). This explicitness is a Visual Basic peculiarity, verbose but very clear when reading.
  • Type tests: TypeOf v Is Bus tests the run-time type; TryCast(v, IChargeable) converts if possible and gives Nothing otherwise, without throwing. (DirectCast throws if the conversion fails; CType also performs value conversions.)

Exercise 1 shows the difference between Overrides and Shadows: an overridden method is chosen by the object's real type, a shadowed one by the variable's declared type. Shadows is occasionally needed and almost always surprising; prefer Overridable and Overrides.

Worked examplesH

Events and structures

Definition— Event

A notification a class can send to any number of listeners. The class declares it with Event and sends it with RaiseEvent; listeners attach handlers with Handles (for a variable declared WithEvents) or AddHandler (at run time). The class does not need to know who is listening.

vb
Option Strict On

' A class that raises an event when something interesting happens.
Public Class Thermostat
    Public Event TemperatureChanged(sender As Object, celsius As Double)
    Public Event TooHot As EventHandler

    Private _celsius As Double = 20

    Public Sub SetTemperature(value As Double)
        If value = _celsius Then Return
        _celsius = value
        RaiseEvent TemperatureChanged(Me, value)
        If value > 30 Then RaiseEvent TooHot(Me, EventArgs.Empty)
    End Sub
End Class

' A structure is a value type: assignment copies it.
Public Structure Reading
    Public Celsius As Double
    Public Location As String
End Structure

Module Program
    ' WithEvents + Handles: the classic Visual Basic way to wire up events.
    WithEvents livingRoom As New Thermostat()

    Sub OnChanged(sender As Object, celsius As Double) Handles livingRoom.TemperatureChanged
        Console.WriteLine($"living room is now {celsius} °C")
    End Sub

    Sub Main()
        livingRoom.SetTemperature(22.5)

        ' AddHandler connects a handler at run time, here a lambda.
        AddHandler livingRoom.TooHot, Sub(s, e) Console.WriteLine("warning: too hot, opening the windows")
        livingRoom.SetTemperature(31)
        livingRoom.SetTemperature(31)      ' no change, so no events

        Dim first As New Reading With {.Celsius = 18, .Location = "porch"}
        Dim second = first                 ' a copy
        second.Celsius = 25
        Console.WriteLine($"{first.Location}: {first.Celsius}, copy: {second.Celsius}")
    End Sub
End Module

It prints:

text
living room is now 22.5 °C
living room is now 31 °C
warning: too hot, opening the windows
porch: 18, copy: 25
  • TemperatureChanged is declared with its own parameter list; TooHot uses the standard .NET EventHandler signature (sender As Object, e As EventArgs), which is what framework events use.
  • WithEvents and Handles connect a handler at compile time: OnChanged runs whenever livingRoom raises TemperatureChanged. This is exactly the mechanism behind Windows Forms code such as Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click, which the designer generates when you double-click a button.
  • AddHandler connects a handler at run time, here a lambda; RemoveHandler disconnects one. Use it for objects created while the program runs.
  • Setting the same temperature again raised nothing, because SetTemperature returns early when nothing changed: a class decides when its events are worth sending.

Structures (Structure ... End Structure) are value types: assigning one copies all its data, so changing second left first unchanged. Use a structure for a small value that is naturally copied, such as a point, a reading or a money amount; use a class for anything with identity or behaviour. Mutable structures with public fields, as in this example, are kept simple for demonstration; in real code, make structures immutable (ReadOnly fields set in Sub New).

Worked examplesH

Identity, equality and Nothing

Two questions are easy to confuse: are these two variables the same object, and do these two objects mean the same thing? Visual Basic answers the first with Is and the second with Equals, which a class can override.

vb
Option Strict On

Public NotInheritable Class Isbn
    Public ReadOnly Property Digits As String

    Public Sub New(text As String)
        Digits = text.Replace("-", "")
    End Sub

    ' Two Isbn objects are equal when their digits are equal.
    Public Overrides Function Equals(obj As Object) As Boolean
        Dim other = TryCast(obj, Isbn)
        Return other IsNot Nothing AndAlso other.Digits = Digits
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return Digits.GetHashCode()
    End Function
End Class

Public Class Member
    Public Property Name As String
    Public Property Phone As String
End Class

Module Program
    Sub Main()
        Dim a As New Isbn("978-0-00-000000-2")
        Dim b As New Isbn("9780000000002")
        Console.WriteLine($"same object? {a Is b}; equal? {a.Equals(b)}")

        ' Equal objects must have equal hash codes, or collections misbehave.
        Dim catalogue As New HashSet(Of Isbn) From {a}
        Console.WriteLine($"catalogue contains b? {catalogue.Contains(b)}")

        ' Nothing, ?. and If(): working safely with references that may be missing.
        Dim members As New List(Of Member) From {
            New Member With {.Name = "Ana", .Phone = "+351 21 000 0000"},
            New Member With {.Name = "Bilal"},
            Nothing
        }
        For Each m In members
            Dim phoneLength = If(m?.Phone?.Length, 0)
            Console.WriteLine($"{If(m?.Name, "(empty slot)")}: {phoneLength} characters of phone number")
        Next
    End Sub
End Module

It prints:

text
same object? False; equal? True
catalogue contains b? True
Ana: 16 characters of phone number
Bilal: 0 characters of phone number
(empty slot): 0 characters of phone number
  • a Is b is False: two separate objects. a.Equals(b) is True, because Isbn overrides Equals to compare the digits, ignoring hyphens.
  • Override GetHashCode whenever you override Equals. Hash-based collections such as HashSet and Dictionary look in the bucket given by the hash code before calling Equals; with mismatched hash codes, catalogue.Contains(b) would wrongly be False.
  • The null-conditional operator ?. (Visual Basic 14) returns Nothing instead of failing when the object on its left is Nothing, and chains: m?.Phone?.Length is Nothing if either the member or the phone is missing. If(value, fallback) then supplies a default. Before ?. existed, code needed nested If ... IsNot Nothing checks, which you will see in older programs.
  • Dim phoneLength = If(m?.Phone?.Length, 0) infers an Integer, because If combines a nullable Integer with the fallback 0.
History & global context

How Visual Basic became object-oriented

Classic Visual Basic grew objects gradually. Version 4 (1995) added class modules, so programmers could define their own types with properties and methods, built on Microsoft's COM component technology. But there was no implementation inheritance: a class could implement an interface, and had to reuse code by containing other objects. Many large VB6 systems are structured around these COM classes, and some are still called from other languages today through COM interop.

Visual Basic .NET (2002) brought full object orientation: inheritance with Inherits, Overridable and MustInherit, constructors with Sub New, Shared members, structured exceptions and free threading, all sharing the .NET type system with C#. That change is why VB6 code could not simply be recompiled, and why VB.NET classes and C# classes can inherit from each other across projects today.

ExplanationH

Object design in maintained Visual Basic code

Visual Basic code written for Windows Forms often puts everything into the form class: data access, validation, calculations and display, all in button-click handlers. It works, and it is hard to test or reuse. The standard improvement, step by step, is to move rules into separate classes that know nothing about the form (a LoanPolicy, an InvoiceCalculator), give them clear properties and methods, and let the form only gather input and show results. Those classes can then be unit-tested, shared with other applications, and, if needed, moved to C# without touching the user interface.

Partial classes and designer files

Open a Windows Forms project and each form appears as two files: MainForm.vb, where you write code, and MainForm.Designer.vb, which the visual designer writes. Both declare Partial Class MainForm; the compiler joins the parts into one class. The designer file creates the controls (declared WithEvents, so that Handles clauses can refer to them), sets their properties and lays them out. Do not edit it by hand unless you must: the designer regenerates it, and a broken designer file stops the form opening in Visual Studio. Your own code, in the other file, sees every control as an ordinary field of the class. The same Partial mechanism is used by other code generators, so you can extend generated classes without touching generated code.

Other habits worth adopting: keep fields Private and expose properties; make classes NotInheritable unless they are designed for inheritance; prefer interfaces over deep inheritance trees; and always turn on Option Strict, which matters even more with objects, because late binding on Object variables hides mistakes in member names until run time.

Common misconceptionsH

Common misconceptions

Misconception

"Shadows is the same as Overrides." Overriding replaces the method for every caller, whatever the variable's declared type. Shadowing only hides it when the object is accessed through the derived type; through a base-class variable, the base version still runs.

Misconception

"A Module and a Class are interchangeable." A module cannot be instantiated, cannot inherit or be inherited, and its members are shared and visible without qualification throughout the namespace. A class can have many instances, each with its own data.

Misconception

"= compares objects." For objects, use Is to ask whether two variables refer to the same object, and Equals (or an overloaded = operator, if the class defines one) to compare contents. Strings are the exception: = compares their text.

Exercises

Exercises

1. Classes, interfaces and events

StretchComputational

What does this program print?

Option Strict On

Public Class Animal
    Public Overridable Function Speak() As String
        Return "..."
    End Function

    Public Function Kind() As String
        Return "animal"
    End Function
End Class

Public Class Dog
    Inherits Animal

    Public Overrides Function Speak() As String
        Return "Woof"
    End Function

    Public Shadows Function Kind() As String
        Return "dog"
    End Function
End Class

Module Program
    Sub Main()
        Dim a As Animal = New Dog()
        Dim d As Dog = New Dog()
        Console.WriteLine($"{a.Speak()} {a.Kind()} {d.Kind()}")
    End Sub
End Module

2. Classes, interfaces and events

CoreComputational

What does this program print?

Option Strict On

Public Class Box
    Public Value As Integer
End Class

Public Structure Cell
    Public Value As Integer
End Structure

Module Program
    Sub Main()
        Dim b1 As New Box With {.Value = 1}
        Dim b2 = b1
        b2.Value = 2
        Dim c1 As New Cell With {.Value = 1}
        Dim c2 = c1
        c2.Value = 2
        Console.WriteLine($"{b1.Value}{c1.Value}")
    End Sub
End Module

3. Classes, interfaces and events

CoreComputational

What does this program print?

Option Strict On

Public Class Counter
    Public Event Reached(n As Integer)
    Private _n As Integer

    Public Sub Increment()
        _n += 1
        If _n Mod 3 = 0 Then RaiseEvent Reached(_n)
    End Sub
End Class

Module Program
    Sub Main()
        Dim c As New Counter()
        Dim heard As Integer = 0
        AddHandler c.Reached, Sub(n) heard += n
        For i As Integer = 1 To 10
            c.Increment()
        Next
        Console.WriteLine(heard)
    End Sub
End Module

4. Classes, interfaces and events

Warm-upHuman

You are translating a Visual Basic class to C#. Which mappings are correct? (Choose all that apply.)

Choose all that apply

5. Classes, interfaces and events

CoreHuman

In the lesson, ElectricScooter declares Public ReadOnly Property Battery As Integer Implements IChargeable.BatteryPercent. Which statement is true?

Choose one

6. Classes, interfaces and events

StretchHuman

A colleague overrides Equals in the Isbn class but forgets GetHashCode. What can go wrong?

Choose one

Further reading and resources