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:
To run the program, save it as Methods.vb
and use the Visual Basic compiler:
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.