Can we overload the method in the same class?
Yes, you can definitely overload methods within the same class. Method overloading involves defining multiple methods within the same class with the same name but different parameter lists. This allows you to provide different ways to call a method based on the type or number of arguments passed.
Here's a simple example in C# demonstrating method overloading within the same class:
using System;
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
int result1 = calculator.Add(5, 10);
double result2 = calculator.Add(3.5, 2.8);
int result3 = calculator.Add(2, 4, 6);
Console.WriteLine("Result 1: " + result1);
Console.WriteLine("Result 2: " + result2);
Console.WriteLine("Result 3: " + result3);
}
}
In this example, the Calculator class has three Add methods with different parameter lists:
-
'Add(int a, int b)' - Adds two integers and returns an integer result.
- 'Add(double a, double b)' - Adds two doubles and returns a double result.
- 'Add(int a, int b, int c)' - Adds three integers and returns an integer result.
When you run the program, you'll see the following output:
Result 1: 15
Result 2: 6.3
Result 3: 12
Each of the overloaded 'Add' methods can have its own implementation, and the appropriate method to call is determined at compile time based on the arguments provided.