Method Overloading in C#
Learn how to create multiple methods with the same name but different parameters in C#.
Table of Contents
- What is Method Overloading?
- Why Use Method Overloading?
- Rules
- Examples
- Best Practices
- Summary
What is Method Overloading?
Method overloading allows multiple methods to have the same name, provided they have different parameter lists. The compiler decides which method to call based on the number, type, or order of parameters.
Note: Method overloading is an example of compile-time polymorphism.
Why Use Method Overloading?
- Improves code readability.
- Reduces the need for multiple method names.
- Allows the same operation to work with different inputs.
Simple Example
static void Display()
{
Console.WriteLine("Hello");
}
static void Display(string name)
{
Console.WriteLine("Hello " + name);
}
Overloading with Different Number of Parameters
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
Overloading with Different Data Types
static int Multiply(int a, int b)
{
return a * b;
}
static double Multiply(double a, double b)
{
return a * b;
}
Tip: Use overloading when methods perform the same logical task but accept different input types.
Rules for Method Overloading
| Allowed | Not Allowed |
|---|---|
| Different number of parameters | Changing only the return type |
| Different parameter types | Same parameter list with same types |
| Different parameter order (different types) | Duplicate method signatures |
Common Mistake: You cannot overload a method by changing only its return type. The parameter list must be different.
Complete Example
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static double Add(double a, double b)
{
return a + b;
}
static void Main()
{
Console.WriteLine(Add(10,20));
Console.WriteLine(Add(5.5,2.5));
}
}
Output
30
8
Best Practices
- Keep overloaded methods related to the same task.
- Use meaningful parameter names.
- Avoid creating too many overloads that confuse users.
- Document each overload clearly.
Summary
| Concept | Description |
|---|---|
| Method Overloading | Same method name with different parameters. |
| Compile-time Polymorphism | Method selected during compilation. |
| Return Type | Cannot overload by return type alone. |
Interview Questions
- What is method overloading?
- Can methods be overloaded using only the return type?
- What is compile-time polymorphism?
- What are the rules of method overloading?
Practice Exercise
- Create overloaded methods to calculate the area of a square and rectangle.
- Create overloaded methods for displaying employee details.
- Overload a method using int and double parameters.
FAQ
Can constructors be overloaded?
Yes. Constructors can also be overloaded.
Can static methods be overloaded?
Yes. Static methods support method overloading.
Next Tutorial: Recursion in C#
No comments:
Post a Comment