Table of Content
- Overview on Overloading in C#
- What is Method Overloading in C#
- What is the Use of Method Overloading?
- How does Method Overloading work in C#?
- Types of Method Overloading in C#
- Real Life Example
- Rules
Overview on Overloading in C#
In Overloading in C#, Polymorphism is a concept of object-oriented programming which defines the ability of an object, a variable, or a method to assume multiple forms during compile/run time. Real-time factors such as data, parameters, return an object, etc., determine what form the object/method/variable will take. This allows the programmer to code in more generic rather than specific. E.g., you eat fruits. How you eat fruits depends on the fruit provided to you in real-time. You eat an apple right away, whereas you peel a banana before eating. Simple.
What is Method Overloading in C#?
Method Overloading is the compile-time implementation of the concept of Polymorphism. Developers can define similar methods by the same name, differing in either the number of arguments, order of arguments, or type of arguments. In the example of fruits, you need not define separate methods for each fruit (eatApple, eat the banana, etc.). You can use the same name to eat fruit and pass different parameters to it. The compiler would automatically call the appropriate method.
Let us take the perspective of C# now. In the most simple terms, Method Overloading in C# is when you have two or more methods with the same name but different signatures. This can be achieved in various ways:
- The different number of parameters.
- Different types of parameters.
- Different order of parameters.
- Optional parameters.
- Named arguments.
What is the Use of Method Overloading?
When you do not want to declare more than one method for a similar type of method for similar tasks to be performed and want to use the same method in different ways, for example, different inputs, different order, different number of inputs for the same methods, you should use method overloading.
Let’s take a real-life example. We are coding for a calculator where you are provided to code for the sum part of the calculator. All the numbers which the user is entering should be added to each other and return the sum of all the number entered.
There is a restriction. Users can not add more than three numbers in one go.
Here are the steps to do it easily:
- Declare a method that should sum all the numbers passed in parameters
- The numbers of parameters passed would do method overloading.
- The method should return the sum of all the numbers entered.
Syntax
Here is the syntax of method overloading.
//declare the parameters in method
public void method1 (parameter1, parameter2)
{
//some statement
}
public void method1(parameter2, parameter1)
{
//some statement to be executed
}
//in main method pass the parameters while declaring these methods
public static void Main(Strings[] args)
{
class object=new class();
object.method(2, 3) //value of parameter
object.method(3, 2) //value of parameter by changing the order
}
}
How does Method Overloading work in C#?
So, how is the appropriate method called based on the arguments/parameters? Well, the compiler checks for each method definition during compilation and binds the method calls to respective definitions. In case there are two methods with the same name, the compiler then checks the signature of the methods and binds the appropriate definition to the call. Even if the signatures can’t resolve the ambiguity, the compiler looks for the implicit conversion of arguments to match the signatures. If an implicit conversion results in a signature match, the binding is done. If not, the compiler generates an error.
We shall look at various examples throughout this article to understand the working of the compiler in various types of Method Overloading.
Types of Method Overloading in C#
Here we discuss the various types of method overloading in C# are given below:
1. Different Number of Parameters
The first and the simplest category of method overloading is when the methods have a different number of parameters in their signatures.
Code:
The example below is pretty straight-forward and is a no-brainer.
using System;
public class Program
{
public static void Main()
{
Func(10);}
public static void Func(int a)
{
Console.WriteLine("Single Parameter");
}public static void Func(int a, int b)
{
Console.WriteLine("Multiple Parameters");
}
}
Output:
2. Different Type of Parameters
When the method signatures have a parameter(s) that differ in the types. The number of parameters may or may not be the same.
Example #1
In the example below, both methods expect a single argument. So, based on the type of the argument passed during the method call, the compiler binds the appropriate method definition.
Code:
using System;
public class Program
{
public static void Main()
{
Func("Hello World");
}
public static void Func(int a)
{
Console.WriteLine("Integer Parameter");
}
public static void Func(string b)
{Console.WriteLine("String Parameter");
}
}
Output:
Example #2
Now, let us give the compiler something to think. We would overload a double and a float type method. We know that an integer can always be implicitly converted into a float type as well as a double type.
When we pass an integer argument, the compiler checks for implicit conversion and finds that the best possible conversion is an integer to float. Hence, the float method is called.
Code:
using System;
public class Program
{
public static void Main()
{
Func(10);
}
public static void Func(double a)
{
Console.WriteLine("Double Parameter");
}
public static void Func(float b)
{
Console.WriteLine("Floating Point Parameter");
}
}
Output:
3. Different Order of Parameters
When the number and type of arguments are the same, but the order in which they are passed differs.
Example #1
The example below is pretty straight-forward.
Code:
using System;
public class Program
{
public static void Main()
{
Func(10, 0.1);
}
public static void Func(int a, double b)
{
Console.WriteLine("Int-Double Parameters");
}
public static void Func(double a, int b)
{
Console.WriteLine("Double-Int Parameter");
}
}
Output:
Example #2
What would happen, when we pass two integer arguments in the example above? Let’s find out.
Code:
Func(10, 1);
Output:
4. Optional Parameters
When we define an optional parameter in the method signature, the compiler treats it as method overloading.
Note: This takes precedence over Implicit conversion.
Let us understand this with an example.
Example
In the example below, we give the compiler two choices. Either it can implicitly convert the argument to match the method signature. Or it can pass the default value of the optional argument. The compiler prefers the latter approach.
Code:
using System;
public class Program
{
public static void Main()
{
Func(10);
}
public static void Func(int a, int b = 1)
{
Console.WriteLine("Int-Int Parameters");
}
public static void Func(double a)
{
Console.WriteLine("Double Parameter");
}
}
Output:
5. Named Arguments
C# has another feature of passing in the name of the arguments while calling the method. This helps in method overloading as well. Developers can choose to call a particular method even if the argument passed would have by default called another method. Although, the overloaded methods must differ in the signature.
Example
In the example below, we instruct the compiler to call a particular method by passing the name of the parameter. The compiler then suspends its logic of determining the best-suited method.
Code:
using System;
public class Program
{
public static void Main()
{
Func(b: 10);
}
public static void Func(int a)
{
Console.WriteLine("Int-Int Parameters");
}
public static void Func(double b)
{
Console.WriteLine("Double Parameter");
}
}
Output:
6. Generic Method Overloading
You can define multiple methods in C# with the same name but different parameter types and one or more of those parameters can be generic By using generic method overloading. This allows the method to function with various types of data while preserving type safety. When you want to write reusable, adaptable code that can work with different types without compromising compile-time type checking, generic methods come in handy.
Example
using System;
public class MaximumFinder
{
// Generic method to find the maximum of two values of the same type
public T FindMax<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
public static void Main()
{
MaximumFinder finder = new MaximumFinder();
// Example with integers
int maxInt = finder.FindMax(5, 10);
Console.WriteLine($"Max Int: {maxInt}");
// Example with doubles
double maxDouble = finder.FindMax(3.5, 7.2);
Console.WriteLine($"Max Double: {maxDouble}");
// Example with strings
string maxString = finder.FindMax("apple", "orange");
Console.WriteLine($"Max String: {maxString}");
}
}
Output:
7. Params Array Overloading
You can define a method parameter in C# that accepts a variable number of arguments by using the params array. It gives you the ability to give a method an arbitrary number of parameters of the same type, increasing the method’s flexibility.
Example
using System;
public class Program
{
public static void Main()
{
// Calling the Sum method with different numbers of arguments
int result1 = Sum(1, 2, 3, 4, 5);
int result2 = Sum(10, 20, 30);
Console.WriteLine("Result 1: " + result1);
Console.WriteLine("Result 2: " + result2);
}
// Method using a params array for variable number of integers
public static int Sum(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
return sum;
}
}
Output
8. Constructor Overloading
Object-oriented programming languages, such as C#, have a feature called constructor overloading that allows a class to have multiple constructors with distinct parameter lists. A class object can be initialized in a different way using each constructor. These constructors are distinguished by the compiler according to the quantity, kind, and arrangement of their parameters.
Example
using System;
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
// Default constructor
public Car()
{
Make = "Unknown";
Model = "Unknown";
Year = 0;
}
// Constructor with make and model
public Car(string make, string model)
{
Make = make;
Model = model;
Year = 0; // Default year
}
// Full constructor with all details
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
// Display method
public void DisplayCarInfo()
{
Console.WriteLine($"Make: {Make}, Model: {Model}, Year: {Year}");
}
}
class Program
{
static void Main()
{
// Using the default constructor
Car car1 = new Car("Mercedes", "Maybach", 2001);
car1.DisplayCarInfo();
Car car2 = new Car("Toyota", "Camry", 2006);
car2.DisplayCarInfo();
Car car3 = new Car("Ford", "Mustang", 2022);
car3.DisplayCarInfo(); // Output: Make: Ford, Model: Mustang, Year: 2022
}
}
Output:
Real Life Example
Now, let’s look at an actual example of method overloading in a messaging application simulation using a MessagingService class.
using System;
public class MessagingService
{
// SendTextMessage method with basic parameters
public void SendTextMessage(string recipient, string message)
{
Console.WriteLine($"Sending text message to {recipient}: {message}");
}
// SendTextMessage method with additional parameter for priority
public void SendTextMessage(string recipient, string message, int priority)
{
Console.WriteLine($"Sending high-priority text message to {recipient}: {message}");
// Additional logic for high-priority messages
}
// SendImageMessage method with image URL
public void SendImageMessage(string recipient, string imageUrl)
{
Console.WriteLine($"Sending image message to {recipient}: {imageUrl}");
}
// SendImageMessage method with additional caption
public void SendImageMessage(string recipient, string imageUrl, string caption)
{
Console.WriteLine($"Sending image message to {recipient}: {imageUrl} (Caption: {caption})");
}
}
class Program
{
static void Main()
{
MessagingService messagingService = new MessagingService();
// Sending a basic text message
messagingService.SendTextMessage("Alice", "Hello, how are you?");
// Sending a high-priority text message
messagingService.SendTextMessage("Bob", "Emergency!", 1);
// Sending an image message without a caption
messagingService.SendImageMessage("Charlie", "https://example.com/image.jpg");
// Sending an image message with a caption
messagingService.SendImageMessage("David", "https://example.com/pic.jpg", "Beautiful sunset");
}
}
Output
Explanation
The MessagingService class serves as an illustration of method overloading for sending both text and picture messages. Different parameter sets for the methods enable users to send messages with different levels of detail. This simulates a messaging app where users can send basic messages or messages with extra features like priority or picture captions.
Rules
The following rules must be kept in mind while overloading methods in your C# application.
- The method signature must be different. Either the number of arguments, type of arguments, or order of arguments must be different.
- The return type of the methods does not play any role in method overloading.
- Optional Parameters take precedence over Implicit type conversion when deciding which method definition to bind.
- Implicit type conversion takes precedence over the parent class method.
Exercise – To understand this, here is a little exercise for you. Create a parent class with a method that expects an integer Inherit a child class. Overload the method from the parent class in the child class such that the child class method expects a double type argument. Create an object of child class and call the overloaded method passing an integer. See what happens.
Conclusion
Method overloading is a fairly powerful concept. It is very helpful in writing elegant code. Yet, it can go to an extent when tens of methods are overloaded, and the developer has to refer the method definitions while debugging the erroneous calls. To avoid this, it is often suggested to name your methods differently when overloading tends to scale to a higher level.
Recommended Articles
We hope that this EDUCBA information on “Overloading in C#” was beneficial to you. You can view EDUCBA’s recommended articles for more information.