04 Feb C# Method Overloading
In C#, we can easily create and call methods with similar names and different parameters. Two or more methods can have similar names in C#, for example:
int Example(int age) int Example(int marks, int rank) float Example(float points)
In the above example, note the Method name is the same, but the parameters are different. Therefore, the concept of overloading works by changing the,
- Number of Arguments
- Type of Arguments
Example 1 – Overloading Methods in C#
Let us see an example where we have methods with similar name and arguments with similar datatypes:
using System;
namespace Demo
{
public class Studyopedia
{
public static int ProdMethod(int x,int y){
return x * y;
}
public static int ProdMethod(int w, int x, int y, int z)
{
return w * x * y * z;
}
static void Main()
{
int mul1 = ProdMethod(2, 3);
int mul2 = ProdMethod(5, 6, 7, 8);
Console.WriteLine("Product of two numbers = {0}",mul1);
Console.WriteLine("Product of four numbers = {0}",mul2);
}
}
}
Output
Product of two numbers = 6 Product of four numbers = 1680
Example 2 – Overloading Methods in C#
Let us see an example where we have methods with similar name but arguments with different datatypes:
using System;
namespace Demo
{
public class Studyopedia
{
// Method 1
public static int ProdMethod(int x,int y){
return x * y;
}
// Method 2 with similar name but arguments with different datatypes
public static float ProdMethod(float x,float y){
return x * y;
}
// Method 3 with similar name but arguments with different datatypes
public static double ProdMethod(double x,double y){
return x * y;
}
static void Main()
{
// Callthe three methods
int mul1 = ProdMethod(2, 3);
float mul2 = ProdMethod(5.7f, 7.8f);
double mul3 = ProdMethod(8.25, 6.27);
Console.WriteLine("Product of two int numbers = {0}",mul1);
Console.WriteLine("Product of two float numbers = {0}",mul2);
Console.WriteLine("Product of two double numbers = {0}",mul3);
}
}
}
Output
Product of two int numbers = 6 Product of two float numbers = 44.46 Product of two double numbers = 51.7275
No Comments