Algorithm
Method overloading in C# allows you to define multiple methods with the same name in the same class or different classes within the same inheritance hierarchy. These methods must have different parameter lists. Overloaded methods provide flexibility and make your code more readable.
Code Examples
#1 By changing the Number of Parameters in C#
Code -
C# Programming
using System;
namespace MethodOverload {
class Program {
// method with one parameter
void display(int a) {
Console.WriteLine("Arguments: " + a);
}
// method with two parameters
void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}
static void Main(string[] args) {
Program p1 = new Program();
p1.display(100);
p1.display(100, 200);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
Arguments: 100 and 200
#2 By changing the Data types of the parameters in C#
Code -
C# Programming
using System;
namespace MethodOverload {
class Program {
// method with int parameter
void display(int a) {
Console.WriteLine("int type: " + a);
}
// method with string parameter
void display(string b) {
Console.WriteLine("string type: " + b);
}
static void Main(string[] args) {
Program p1 = new Program();
p1.display(100);
p1.display("DevsEnv");
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
string type: DevsEnv
#3 By changing the Order of the parameters in C#
Code -
C# Programming
using System;
namespace MethodOverload {
class Program {
// method with int and string parameters
void display(int a, string b) {
Console.WriteLine("int: " + a);
Console.WriteLine("string: " + b);
}
// method with string andint parameter
void display(string b, int a) {
Console.WriteLine("string: " + b);
Console.WriteLine("int: " + a);
}
static void Main(string[] args) {
Program p1 = new Program();
p1.display(100, "Programming");
p1.display("DevsEnv", 400);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
string: Programming
string: DevsEnv
int: 400
Demonstration
C# Programming Method Overloading