Function/Method Overloading in C#
In previous post , we learned what are the classes and methods and objects. If you have not seen that, here is the link to it.
Classes in C#
What is Function Overloading
Function Overloading is nothing but a function/Method with the same name but multiple function definition. The function are different from each other by Function Definition and the number of parameters passed to the function.
Function Overloading is one of the way we can implement static Polymorphism. Polymorphism stands for the term having multiple forms. The Polymorphism have two types .
1)Static .
2)Dynamic .
The function overloading is a Static Polymorphism.
Example
using System;
namespace FunctionOverloading
{
class PrintData
{
public void show(int a)
{
Console.WriteLine("Age of Raju is {0}", a);
}
public void show(double amount)
{
Console.WriteLine("Amount he has taken is {0}",amount);
}
public void show(string s)
{
Console.WriteLine("Name is {0}", s);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
PrintData p = new PrintData();
p.show(20);
p.show(500.45);
p.show("Raju");
}
}
namespace FunctionOverloading
{
class PrintData
{
public void show(int a)
{
Console.WriteLine("Age of Raju is {0}", a);
}
public void show(double amount)
{
Console.WriteLine("Amount he has taken is {0}",amount);
}
public void show(string s)
{
Console.WriteLine("Name is {0}", s);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
PrintData p = new PrintData();
p.show(20);
p.show(500.45);
p.show("Raju");
}
}
Outout
Age of Raju is 20
Amount he has taken is 500.45
Name is Raju
Amount he has taken is 500.45
Name is Raju
Explanation
public void showfor three times to print three different values of different data type.int,double and string respectively.
Example 2
using System;
namespace Overloading_2
{
class Calculate
{
public void calculation(int a ,int b)
{
Console.WriteLine("Addition of two numbers is {0} ",a+b);
}
public void calculation(int a,int b,int c)
{
Console.WriteLine("Addition of three numbers is {0} ", a + b + c);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new Calculate();
c.calculation(3, 3);
c.calculation(2, 4, 3);
}
}
namespace Overloading_2
{
class Calculate
{
public void calculation(int a ,int b)
{
Console.WriteLine("Addition of two numbers is {0} ",a+b);
}
public void calculation(int a,int b,int c)
{
Console.WriteLine("Addition of three numbers is {0} ", a + b + c);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new Calculate();
c.calculation(3, 3);
c.calculation(2, 4, 3);
}
}
Output
Addition of two numbers is 6
Addition of three numbers is 9
Addition of three numbers is 9
Explanation
This is how method overloading is implemented.
Function/Method Overloading in C#
Reviewed by LanguageExpert
on
April 15, 2018
Rating:
No comments