Method overloading in C#

Method overloading is a feature in C# that allows a class to have multiple methods with the same name but with different parameters. This can be useful in situations where a single method may be used in multiple ways, or where a method needs to handle a variety of input types.

To overload a method in C#, you simply need to define multiple methods with the same name but with different parameters. For example, let's say we have a class called Calculator, and we want to create an overloaded method called "Add" that can handle both integers and doubles. Here's an example of how we might define the methods:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } }

As you can see, we have defined two methods called "Add", one that takes two integers as parameters and another that takes two doubles. Now, when we call the "Add" method on an instance of the Calculator class, the correct method will be called based on the types of the parameters we pass in:

Calculator calc = new Calculator(); int result = calc.Add(2, 3); // result is 5 double result2 = calc.Add(2.5, 3.2); // result2 is 5.7

It's important to note that the C# compiler uses the type and number of parameters to determine which overloaded method to call. This means that the order of the parameters also matters when overloading methods.

Additionally, you can also use the params keyword to allow a variable number of arguments to be passed to the method.

class Calculator { public int Add(int a, int b) { return a + b; } public int Add(params int[] numbers) { int sum = 0; foreach (int num in numbers) { sum += num; } return sum; } }

In this example, you can pass any number of integers to the Add method and it will sum them up.

In conclusion, method overloading is a powerful feature in C# that allows a class to have multiple methods with the same name but with different parameters. This can be useful in situations where a single method may be used in multiple ways, or where a method needs to handle a variety of input types. It's important to note that the C# compiler uses the type and number of parameters to determine which overloaded method to call and you can use the params keyword to allow a variable number of arguments to be passed to the method.

Comments

Popular posts from this blog

What are tuple in c#?

How to read/write google sheet in C#?