Visual Basic.NET 2008 > Programming Fundamentals Named Arguments - Visual Basic 2008You 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:
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:
you can call it this way:
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:
Then call the Contact() function from within a button's Click event with the following statement:
You'll see the following in the Immediate window:
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 | |||||