- A Function overloading can be compared with person overloading
- If a person has already some work to do and we are assigning additional work to the person then person will be overloaded
- In the same way, a function will have already some work to do and if we assign a different work to the same function, then we say function is overloaded
- A function will be overloaded in two situations
- When data types of the argument are changed
- When numbers of arguments are changed
Definition
- Providing new implementation to a function with different signature is known as function overloading
- In general function overloading is implemented within the same class
When data types of the argument are changed
- Consider a function like
Sum(int a, int b)
{
}
- We can call the above functions by using two arguments like Add (1, 9)
- But if we want to call the above function by passing different data type value like Add (99.9, 8), we cannot use the above function and we overload the function like
Sum (double a, int b)
{
….
….
}
When numbers of arguments are changed
- Consider a function like
Sum (int a, int b)
{
….
….
}
- We can call the above function by passing two arguments like Add(1,9)
- If we want to call the above function with different number of argument like Add(1, 9, 44)
- We cannot use the above function and we overload our function and we overload the function like
Add(int a, int b, int c)
{
….
….
}
Example:-
ClsFOExample
|
public int Sum(int a,int b)
public
int Sum(int
a, int b, int
c)
public
double Sum(double
a, int b)
|
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
namespace
CAFOvedrloading
{
class ClsFOExample
{
public int Sum(int a,int b)
{
return
a + b;
}
public int Sum(int a, int b, int c)
{
return
a + b + c;
}
public
double Sum(double
a, int b)
{
return
a + b;
}
}
class ClsFOverloading
{
static
void Main(string[]
args)
{
ClsFOExample
obj1 = new ClsFOExample();
Console.WriteLine("sum of the two integer values is :-
"+obj1.Sum(1,9));
Console.WriteLine("Sum of the three integer values is :- "+obj1.Sum(99.9,8));
Console.WriteLine("Sum of the one float value and one integer value
is:-"+obj1.Sum(1,9,44));
Console.ReadLine();
}
}
}
|
Output :-
No comments:
Post a Comment