Visual Basic Methods

So far the only method that has been created is the ‘Main’ method, which is required for a Visual Basic program to run. It is however possible to create other methods that can be used by this ‘Main’ method. A big advantage of doing this is where the same block of code is used multiple times within a program. By putting this code in a separate method, it can be written once and then called any number of times. Doing this also aids in maintaining the program because if the code needs updating it only needs to be done in one place.

In Visual Basic there are two different types of method, a ‘sub’ or subroutine and a function. The difference between the two is that a function can return a value to the code that called it, whereas a subroutine can’t.

In its most simple form, a subroutine can be defined as follows.

Public Shared Sub MethodName()

    ' Statement(s) to execute.

End Sub

Calling this subroutine is simply a case of specifying the name, followed by opening and closing parenthesis.

MethodName()

Below is an example of a subroutine called ‘Message’, that is called from the ‘Main’ method, which displays the message, ‘Hello world!’ out to the console.

Public Shared Sub Main()

    Message()

End Sub

Public Shared Sub Message()

    Console.WriteLine("Hello world!")

End Sub

When a subroutine is called, it is possible to pass parameters, so that the values can be used within the block of code it contains. Here, two variables are declared and initialised in the ‘Main’ method, then their values are passed to the ‘Message’ subroutine for use in the message displayed in the console. The ‘WriteLine’ method uses string interpolation to incorporate the values of the parameters into the message.

Public Shared Sub Main()

    Dim name As String = "Bob"
    Dim age As Integer = 30

    Message(name, age)

End Sub

Public Shared Sub Message(ByVal fname As String, ByVal age As Integer)

    Console.WriteLine($"{fname} is {age} years old.")

End Sub

When declaring a subroutine that accepts parameters, the data type must be included. This must match the data type of the value being passed in. In the above example, the parameters are of ‘String’ and ‘Integer’ data types respectively. Notice that the names of the variables included in a method call do not have to match the names of the parameters in the method declaration. This is demonstrated here, where the ‘name’ variable is passed in, but the corresponding parameter is called ‘fname’. The variables passed in must however be in the same order as they are in the method declaration. The method name, along with the order and type of parameters form what is called the Method Signature and ensures that the right method is called.

If it is necessary to return a value, then the second type of method needs to be used, a function.

Public Shared Function FunctionName() As ReturnType

    Return ReturnValue

End Function

The two differences to note between a function and subroutine are that the data type of the value to be returned must be specified and the ‘Return’ keyword is used to pass a value back to the calling code. Parameters can be passed in the same manner as with subroutines.

Functions can be called in much the same way as a subroutine, although as a value can be returned, it can be called as part of a larger statement that assigns the returning value to a variable.

VariableName = FunctionName()

Below is an example of a function, which returns a string incorporating the two parameters passed to it. The result is output to the console.

Public Shared Sub Main()

    Dim name As String = "Bob"
    Dim age As Integer = 30

    Console.WriteLine(Message(name, age))

End Sub

Public Shared Function Message(ByVal fname As String, ByVal age As Integer) As String

    Return $"{fname} is {age} years old."

End Function

Passing by Value and Reference

When passing variables as parameters as shown in the above subroutine and function examples, a copy of the variable value is being passed and not the actual variable. This means that if the parameter values in the method being called are changed, they will not be available to the calling method, even if the names of the parameters match those of the original variables. This is known as ‘Passing by Value’. Each parameter in the above subroutine and function declarations are preceded by ‘ByVal’, which is short for by value, and is used to specify that only a copy of the values are being passed. If ‘ByVal’ were to be replaced with ‘ByRef’ it would mean that the actual variable is being passed and not just its value. This would mean that the variable values could be changed in the method, either subroutine or function, and then be available back in the calling code.

The example below can be used to demonstrate this. There are three lines written out to the console, the middle of which is within a method, in this case a subroutine. Within the method the values of the two variables are changed, meaning that the third line output to the console displays these altered values, as the parameters are passed by reference. If the parameters were passed by value then this third line would include the original variable values. Note that the names of the parameters in the method match those of the variables.

Public Shared Sub Main()

    Dim name As String = "Bob"
    Dim age As Integer = 30

    Console.WriteLine($"{name} is {age} years old.")
    Message(name, age)
    Console.WriteLine($"{name} is {age} years old.")

End Sub

Public Shared Sub Message(ByRef name As String, ByRef age As Integer)

    name = "Fred"
    age = 45

    Console.WriteLine($"{name} is {age} years old.")

End Sub

The resulting output is shown below.

Bob is 30 years old.
Fred is 45 years old.
Fred is 45 years old.

Method Overloading

Method overloading is a feature of Visual Basic, along with many other programming languages, that allows for there to be more than one method, subroutine or function, with the same name, providing the Method Signature is different. As mentioned above, the Method Signature comprises of the method name, along with the order and type of parameters.

Below is an example which contains three methods, in this case functions, named ‘Message’. The first version has no parameters, whilst the second has one ‘String’ parameter and finally, the third, which has one ‘String’ and one ‘Integer’ parameter. Each version returns a string containing a message, that is output to the console, when called from the ‘Main’ method. The second and third versions of the method incorporate the parameters that have been passed.

Public Shared Sub Main()

    Dim name As String = "Bob"
    Dim age As Integer = 30

    Console.WriteLine(Message())
    Console.WriteLine(Message(name))
    Console.WriteLine(Message(name, age))

End Sub

Public Shared Function Message() As String

    Return "Hello world!"

End Function

Public Shared Function Message(ByVal fname As String) As String

    Return $"Hello {fname}!"

End Function

Public Shared Function Message(ByVal fname As String, ByVal age As Integer) As String

    Return $"{fname} is {age} years old."

End Function

The resulting output is as follows.

Hello world!
Hello Bob!
Bob is 30 years old.