Methods in Visual Basic .NET

Our first example demonstrates how to define and use methods in Visual Basic .NET. Here’s the full source code:

Imports System

Public Class Rect
    Public Property Width As Integer
    Public Property Height As Integer

    ' This Area method is defined for the Rect class
    Public Function Area() As Integer
        Return Width * Height
    End Function

    ' Methods can be defined for either reference or value types
    ' Here's an example of a method defined for the Rect class
    Public Function Perim() As Integer
        Return 2 * Width + 2 * Height
    End Function
End Class

Module Program
    Sub Main(args As String())
        Dim r As New Rect With {.Width = 10, .Height = 5}

        ' Here we call the 2 methods defined for our class
        Console.WriteLine("area: " & r.Area())
        Console.WriteLine("perim: " & r.Perim())

        ' In VB.NET, there's no need to explicitly use pointers
        ' The language handles reference types automatically
        Dim rRef As Rect = r
        Console.WriteLine("area: " & rRef.Area())
        Console.WriteLine("perim: " & rRef.Perim())
    End Sub
End Module

To run the program, save it as Methods.vb and use the Visual Basic compiler:

$ vbc Methods.vb
$ mono Methods.exe
area: 50
perim: 30
area: 50
perim: 30

Visual Basic .NET supports methods defined on classes, which are similar to structs in some other languages. In this example, we define a Rect class with Width and Height properties, and two methods: Area and Perim.

The Area method calculates and returns the area of the rectangle. In Visual Basic .NET, we don’t need to explicitly use pointer receivers as in some other languages. The language handles reference types automatically.

The Perim method calculates and returns the perimeter of the rectangle. This demonstrates that methods can be defined directly on the class.

In the Main subroutine, we create an instance of Rect, and then call both methods on this instance. We also demonstrate that you can create a reference to an existing object (rRef) and call methods on it, which will affect the original object.

Visual Basic .NET automatically handles references for objects, so there’s no need to explicitly use pointers or worry about value vs. reference semantics when calling methods.

Next, we’ll look at Visual Basic .NET’s mechanism for defining and implementing interfaces, which provide a way to specify a set of methods that a class must implement.