1. Introduction to Method Overloading
Method overloading is a feature in C# that allows a class to have multiple methods with the same name but with different parameters. The compiler determines which method to call based on the number and types of arguments.
2. Basic Syntax
class Example{// Method with no parameterspublic void MyMethod(){// Method implementation}// Method with one parameterpublic void MyMethod(int x){// Method implementation with one parameter}// Method with two parameterspublic void MyMethod(int x, string y){// Method implementation with two parameters}}
3. Rules for Overloading
- Methods must have the same name.
- Methods must be in the same class.
- Methods must have a different number or type of parameters.
- The return type does not play a role in method overloading.
4. Example: Overloading with Different Parameter Types
class Calculator{public int Add(int a, int b){return a + b;}public double Add(double a, double b){return a + b;}}
5. Example: Overloading with Different Number of Parameters
class Printer{public void Print(string message){Console.WriteLine(message);}public void Print(string message, ConsoleColor color){Console.ForegroundColor = color;Console.WriteLine(message);Console.ResetColor();}}
6. Example: Overloading with Optional Parameters
class Greeter{public void Greet(string name){Console.WriteLine($"Hello, {name}!");}public void Greet(string name, string greeting = "Hello"){Console.WriteLine($"{greeting}, {name}!");}}
7. Conclusion
Method overloading is a powerful feature in C# that allows you to create more flexible and readable code by defining multiple methods with the same name but different parameters. It's important to follow the rules of overloading to avoid ambiguity and ensure proper functionality.
This tutorial covers the basics of method overloading, including syntax, rules, and examples. Practice using method overloading in your C# projects to enhance code organization and improve code readability.