Start C# here

Study C#.. Go ahead ! !

Wednesday, July 30, 2008

Function Overloading

Function overloading is the process of having the same name for functions but having different parameters(function signatures), either in number or in type. Function overloading reduces the complexity of a program. Function overloading helps the user to use functions without changing its name or the return type. To overload a function we need to change the parameters inside the Function. The parameters/function signature(s) should not be the same for another function which need to overloaded.
-------------------------------------------------
class MethodOverloading
{
//Method one
public void Add(int i, int j)
{
Console.WriteLine(i+j);
}
//Method Two
public void Add(string s, string k)
{
Console.WriteLine(s+k);
}
}
--------------------------------------------------
Here in the above code we have two methods with the same name Add. This method is overloaded since the signatures inside it changes in the second method. In the first method we have passed two Integer values as parameters and in the second method we have passed two string values into the method. Now when we call this method, if we are passing two integer values to the method then the first method will be invoked and will be adding the two integers and showing the result to us. In the other case if we are passing two String values into the same function the second method will be invoked and it will be concatenating the two strings and the concatenated string is displayed.
Here when we used function overloading it does not vary in the return type. But the behavior has changed according to the values we pass to the functions.

In the above case Method 1 and Method 2 have the same return Type but are varied in the signature.
Method 1 has two integer parameter and Method 2 has two string parameters.

Now we’ll check some more examples for function overloading..


class MethodOverloading
{
public int Display(int i)
{
return i;
}


public int Display(int j, int k)
{
return j+k;
}
public int Display(int l, int m,int n)
{
return (l+m-n);
}
}
-------------


Here in the above cases in all the functions we have integer parameters. These are also overloaded because the parameters passed to each method vary in number ie; the First method has only one parameter; the second have two parameters and the third have three parameters.

No comments: