- Sub Procedures
- Creating Functions
- Using Optional Arguments
- Passing a Variable Number of Arguments
- Preserving Data Between Procedure Calls
- Understanding Scope
- Handling Runtime Errors
- Unstructured Exception Handling
- Structured Exception Handling
- Introducing Classes and Objects
- Summary
- Q&A
- Workshop
Passing a Variable Number of Arguments
Here's another valuable technique: You can create procedures that can accept a varying number of arguments. You do that with the ParamArray keyword in the argument list, which makes all the arguments passed at that point in the list and after it part of an array. If you use a ParamArray argument, it must be the last argument in the argument list. Here's an example; in this case, the ShowMessage Sub procedure is able to handle a variable number of arguments:
Module Module1 Sub Main() End Sub Sub ShowMessage(ByVal ParamArray Text() As String) . . . End Sub End Module
This means that the Text argument here is really an array of arguments. In this example, we can loop over all the arguments in this array, displaying them like this:
Module Module1 Sub Main() End Sub Sub ShowMessage(ByVal ParamArray Text() As String) Dim intLoopIndex As Integer For intLoopIndex = 0 To UBound(Text) Console.Write(Text(intLoopIndex)) Next intLoopIndex Console.WriteLine("") 'Skip to the next line End Sub End Module
Now you can call ShowMessage with different numbers of arguments, as you see in Listing 3.4.
Listing 3.4 Using Variable Numbers of Arguments (VariableArgs project, Module1.vb)
Module Module1 Sub Main() ShowMessage("Hello there!") ShowMessage("Hello", " there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal ParamArray Text() As String) Dim intLoopIndex As Integer For intLoopIndex = 0 To UBound(Text) Console.Write(Text(intLoopIndex)) Next intLoopIndex Console.WriteLine("") End Sub End Module
Here's what you see when this code runs:
Hello there! Hello there! Press Enter to continue...