A method is said to be overloaded if two or more methods having the same name but different parameters. The difference could be in a number of parameters or types of parameters so that compiler can tell the difference.
The advantage of method overloading is that you don’t have to use different names for the function which does the same task. Method overloading is a way to achieve Compile Time Polymorphism in C#
Method overloading in C# can be achieved in two ways:
- By changing number of arguments
- By changing data type of the arguments
1. C# Method overloading: By changing the data type of Arguments
In this method, the data type is changed although the number of arguments passed remains the same. Also, while calling this method make sure to give the proper parameters accordingly.
Example of C# program for method overloading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; namespace Program { class OverloadMethod { public void display(String name, int roll) { Console.WriteLine("Name: {0} Roll: {1}", name, roll); } public void display(float num1, float num2) { Console.WriteLine("Value of counter: {0}", num1 + num2); } } public class OverloadMain { static void Main(string[] args) { OverloadMethod obj = new OverloadMethod(); // Call functions obj.display("John Mac", 18); obj.display(90.2f, 6.5f); } } } |
Output:
Name: John Mac Roll: 18
Value of counter: 96.7
2. C# Method Overloading: By changing no. of arguments
Another way is by changing the number of arguments that is the number of parameters passed when called. We can also keep the argument empty and it will recognize the method with an empty parameter list.
Example of C# program for method overloading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; namespace Program { class MethodOverload { public void display(String name, int roll) { Console.WriteLine("Name: {0} Roll: {1}", name, roll); } public void display(int counter) { Console.WriteLine("Value of counter: {0}", counter + 1); } } public class OverloadMain { static void Main(string[] args) { MethodOverload obj = new MethodOverload(); // Call functions obj.display("John Mac", 18); obj.display(99); } } } |
Output:
Name: John Mac Roll: 18
Value of counter: 100