Visual Basic.NET 2008 > Programming Fundamentals

Named Arguments - Visual Basic 2008

You learned how to write procedures with optional arguments and how to pass a variable number of arguments to the procedure. The main limitation of the argument-passing mechanism, though, is the order of the arguments. By default, Visual Basic matches the values passed to a procedure to the declared arguments by their order (which is why the arguments you've seen so far are called positional arguments).

This limitation is lifted by Visual Basic's capability to specify named arguments. With named arguments, you can supply arguments in any order because they are recognized by name and not by their order in the list of the procedure's arguments. Suppose you've written a function that expects three arguments: a name, an address, and an email address:

Function Contact(Name As String, Address As String, EMail As String)

When calling this function, you must supply three strings that correspond to the arguments Name, Address, and EMail, in that order. However, there's a safer way to call this function: Supply the arguments in any order by their names. Instead of calling the Contact() function as follows:

Contact("Peter Evans", "2020 Palm Ave., Santa Barbara, CA 90000", _
"PeterEvans@example.com")

you can call it this way:

Contact(Address:="2020 Palm Ave., Santa Barbara, CA 90000", _
EMail:="PeterEvans@example.com", Name:="Peter Evans")

The := operator assigns values to the named arguments. Because the arguments are passed by name, you can supply them in any order.

To test this technique, enter the following function declaration in a form's code:

Function Contact(ByVal Name As String, ByVal Address As String, _
ByVal EMail As String) As String

Debug.WriteLine(Name)
Debug.WriteLine(Address)
Debug.WriteLine(EMail)
Return ("OK")

End Function

Then call the Contact() function from within a button's Click event with the following statement:

Debug.WriteLine( _
Contact(Address:="2020 Palm Ave., Santa Barbara, CA 90000", _
Name:="Peter Evans", EMail:="PeterEvans@example.com"))

You'll see the following in the Immediate window:

Peter Evans
2020 Palm Ave., Santa Barbara, CA 90000
PeterEvans@example.com
OK

The function knows which value corresponds to which argument and can process them the same way that it processes positional arguments. Notice that the function's definition is the same, whether you call it with positional or named arguments. The difference is in how you call the function and not how you declare it.

Named arguments make code safer and easier to read, but because they require a lot of typing, most programmers don't use them. Besides, when IntelliSense is on, you can see the definition of the function as you enter the arguments, and this minimizes the chances of swapping two values by mistake.

Table of Contents

     
 
W3computing.com Copyright 2011 © All Rights Reserved
 
  Home | Useful links | Contact us