What is method overloading in c# with example.
Method overloading in C# allows you to define multiple methods with the same name in the same class, but with different parameter lists. This enables you to use the same method name for different behaviors based on the input parameters.
Here's a simple example:
```csharp code```
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 string Add(string a, string b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
Console.WriteLine(calculator.Add(2, 3)); // Output: 5
Console.WriteLine(calculator.Add(2.5, 3.5)); // Output: 6.0
Console.WriteLine(calculator.Add("Hello, ", "world!")); // Output: Hello, world!
}
}
```
In this example, the `Calculator` class has three `Add` methods with different parameter types. Depending on the arguments you pass when calling the method, the compiler will determine the appropriate version of the method to execute.
Comments
Post a Comment