Method Overloading
Method Overloading
In Method Overloading we have two or more than two methods those have the same name but different parameters.
Method overloading done by three ways.
- The number of parameters change in methods.
- The data types of the parameters change in methods
- The order of parameters change in methods
Number of parameters
In this method overloading, the number of parameters is different in the methods.e.g one method has single parameter and another methods has more than two parameters.
using System;
public class MyCode {
public static int AddDisplay(int one, int two) {
return one + two;
}
public static int AddDisplay(int one, int two, int three) {
return one + two + three;
}
public static int AddDisplay(int one, int two, int three, int four) {
return one + two + three + four;
}
}
public class Program {
public static void Main() {
Console.WriteLine("Addition of two numbers: "+MyCode.AddDisplay(10, 10));
Console.WriteLine("Addition of three numbers: "+MyCode.AddDisplay(5, 10, 20));
Console.WriteLine("Addition of four numbers: "+MyCode.AddDisplay(2, 5, 10, 20));
}
}
OUTPUT
Addition of two numbers: 20
Addition of three numbers: 35
Addition of four numbers: 37
Data types of the parameters
In this method overloading,the data types of parameters is different in the methods.e.g here we have different data types of parameters for same name methods that is use for overloading.
using System;
public class MyCode {
public static int AddDisplay(int one, int two) {
return one + two;
}
public static double AddDisplay(double one, double two, double three) {
return one + two + three;
}
public static float AddDisplay(float one, float two, float three, float four) {
return one + two + three + four;
}
}
public class Program {
public static void Main() {
Console.WriteLine("Addition of two numbers: "+MyCode.AddDisplay(10, 10));
Console.WriteLine("Addition of three numbers: "+MyCode.AddDisplay(5.5D, 10D, 20D));
Console.WriteLine("Addition of four numbers: "+MyCode.AddDisplay(2.5F, 5.5F, 10F, 20F));
}
}
OUTPUT
Addition of two numbers: 20
Addition of three numbers: 35.5
Addition of four numbers: 38
Order of parameters
In this method overloading,the order of data types of parameters is different in same name of methods.for e.g here we can change the order of data types of parameters (i.e int,string) in same name methods (i.e DisplayData)
using System;
public class MyCode {
public void DisplayData(int a, string b) {
Console.WriteLine("Id: " + a);
Console.WriteLine("Name: " + b);
}
public void DisplayData(string b, int a) {
Console.WriteLine("Name: " + b);
Console.WriteLine("Id: " + a);
}
}
public class Program {
public static void Main() {
MyCode m1 = new MyCode();
m1.DisplayData(1, "Roy");
m1.DisplayData("Alexa", 2);
Console.ReadLine();
}
}
OUTPUT
Id: 1
Name: Roy
Name: Alexa
Id: 2