Optional arguments in Visual Basic

Some things that can be accomplished using optional arguments can also be accomplished using overloading. I usually write the function with the most arguments first, and then I do overloaded versions of the function that calls the first version and provide the arguments like this:

Public Sub DoSome(ByVal X As Integer)
	Console.WriteLine(X)
End Sub

Public Sub DoSome()
	DoSome(4)
End Sub

This can also be accomplished using optional parameters. They are declared using the keyword optional. You also need to provide a default value to the optional argument like this:

Public Sub DoSome(Optional ByVal X As Integer = 4)
	Console.WriteLine(X)
End Sub

This last example will effectively be the same for the one that calls the function, who still can call DoSome with one or no parameters. One syntax limitation is that all parameters declared after an optional parameter must also be optional.

As long as the procedure doesn’t contain any parameter arrays, it can be called using named arguments. In this example, the procedure HitMe can be called without named arguments like this: HitMe(1, 2) or using named arguments like this: HitMe(X:=1, Y:=2).

Public Sub HitMe(ByVal X As Integer, ByVal Y As Integer)

The code for calling a function that takes lots of optional arguments without using named arguments is really ugly. It might look something like this:

MyFunction(, , , , , , , , , , , , , , , , , , , , , , 6)

It is not very readable. By specifying the name of the argument you want to pass, the code is much more readable.

MyFunction(OneParameter:=6)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *