When an object’s methods or an assembly’s procedures and methods are called, it’s often appropriate to provide input for the data to be operated on by the code. The values are referred to as parameters, and any object can be passed as a parameter to a Function or Sub.

When passing parameters, be aware of whether the parameter is being passed ‘‘by value’’ (ByVal) or ‘‘by reference’’ (ByRef). Passing a parameter by value means that if the value of that variable is changed, then when the Function/Sub returns, the system automatically restores that variable to the value it had before the call. Passing a parameter by reference means that if changes are made to the value of a variable, then these changes affect the actual variable and, therefore, are still present when the variable returns. This is where it gets a little challenging for new Visual Basic developers. Under .NET, passing a parameter by value indicates only how the top-level reference (the portion of the variable on the stack) for that object is passed. Sometimes referred to as a shallow copy operation, the system copies only the top-level reference value for an object passed by value. This is important to remember because it means that referenced memory is not protected. When you pass an integer by value, if the program changes the value of the integer, then your original value is restored. Conversely, if you pass a reference type, then only the location of your referenced memory is protected, not the data located within that memory location. Thus, while the reference passed as part of the parameter remains unchanged for the calling method, the actual values stored in referenced objects can be updated even when an object is passed by value.

In addition to mandatory parameters, which must be passed with a call to a given function, it is possible to declare optional parameters. Optional parameters can be omitted by the calling code. This way, it is possible to call a method such as PadRight, passing either a single parameter defining the length of the string and using a default of space for the padding character, or with two parameters, the first still defining the length of the string but the second now replacing the default of space with a dash.

Public Function PadRight(ByVal intSize as Integer, _
Optional ByVal chrPad as Char = " "c)
End Function

To use default parameters, it is necessary to make them the last parameters in the function declaration. Visual Basic also requires that every optional parameter have a default value. It is not acceptable to merely declare a parameter and assign it the Optional keyword. In Visual Basic, the Optional keyword must be accompanied by a value that is assigned if the parameter is not passed in.

Source of Information : Wrox Professional Visual Basic 2008

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner