Parameters allow you to pass values to methods. In Visual Basic, it is common convention to always start a parameter off with a lowercase letter. There are two ways to pass parameters: ByVal and ByRef.

  • ByVal - By sending a variable ByVal, or by Value, you are only sending the value rather than the variable. In other words, changing the value of the variable in the method called will not affect the value of the variable once the method has finished executing. This is the default type of parameter.
  • ByRef - By sending a variable ByRef, or by Reference, you are referencing the variable in the first method, not the value. In other words, changing the value of the variable in the method called will affect the value of the variable.

Here is an example of how you may pass a string and an Integer to a function which returns a string:

Private Function MyFunction(ByVal stringname As String, intnum As Integer) As String
  Return stringname & intnum.ToString()
End Function

NOTE: Because I did not define the variable "intnum" as byVal or ByRef, Visual Basic will set it to the default, which is ByVal.

To call this function, we can do the following:

Dim strExample As String
strExample = MyFunction("name", 4)

In this example, strExample will end with a value of "name4." Next, we will discuss method overloading.

Method Overloading

Method overloading is creating multiple methods with the same name, but accepting different types of parameters. One good example of a method that has been overloaded is the ToString() Function. This method can be used on nearly any object, yet they all send different parameters.

This may seem like bad programming. However, there are some scenarios where this can end up being very helpful. For example, if you are accepting a user's input of their age in an input box, the user may enter a number, such as 24. They may also enter a string, such as "Twenty-Four." Using method overloading, you can use the same method name for both of these. Here is an example:

Private Overloads Sub SetUserAge(ByVal age As String)
  'Do something
End Sub

Private Overloads Sub SetUserAge(ByVal age As Integer)
  'Do something
End Sub

By doing this, I can now send a method named "SetUserAge" either a String or an Integer. Notice that in Visual Basic you should use the term "Overloads" in your method to show that you are overloading that method. Obviously, you cannot overload a method with the same type and number of parameters. By doing this, Visual Basic will not know which method you are referring to.

I hope you have enjoyed this Visual Basic tutorial. If you have any questions about any of this, please do not hesitate to email me at jacob@morrisprogramming.com.

Previous

Startup Discount
Small Business?
Contact us for an Enormous Discount!