Monday, May 21, 2007

Overloading Functions

Function overloading provides you with the ability to create multiple functions with the same name, but each working with different parameter types.
For Example:
Static int MaxValue (int[ ] intArray)
{
………………
return maxVal;
}

Static double MaxValue (double[ ] doubleArray)
{
………………
return maxVal;
}
Here both the function names MaxValue() is same but its signature is different. It would be error to define two functions with the same name and signature, but since these two functions have different signatures, this is fine.
The beauty of this type of code is that you don’t have to explicitly specify which of these two functions you wish to use. You simply provide an array parameter, and the correct function will be executed depending on the type of the parameter used.

All aspects of the function signature are included when overloading functions. For Example, you have two different functions that take parameters by value and by reference, respectively:
Static void ShowDouble (ref int val)
{
………………
}

Static void ShowDouble (int val)
{
………………
}
The choice as to which of these versions to use is based purely on whether the function call contains the ref keyword. The following would call the reference version:
ShowDouble (ref val);

And the following would call the value version:
ShowDouble (val);

No comments: