Method Overloading
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 50 of 70.
Method overloading allows you to define multiple methods with the same name but different parameter lists. The compiler determines which version to call based on the arguments you provide.
Each overloaded method must have a unique signature - either a different number of parameters or different parameter types:
public static void Print(string message)
{
Console.WriteLine(message);
}
public static void Print(string message, int times)
{
for (int i = 0; i < times; i++)
Console.WriteLine(message);
}
public static void Print(int number)
{
Console.WriteLine(number);
}// The compiler picks the right version
Print("Hello"); // Calls Print(string)
Print("Hi", 3); // Calls Print(string, int)
Print(42); // Calls Print(int)Overloading differs from optional parameters in an important way. With optional parameters, you have one method that handles multiple scenarios. With overloading, you have separate methods that can contain completely different logic for each case.
Note that return type alone doesn't make methods unique - you cannot have two methods that differ only by what they return. The parameter list must be different. Method overloading is a form of compile-time polymorphism, where the decision about which method to call is made when the code is compiled, not when it runs.
Challenge
EasyLet's build a versatile calculator class that demonstrates the power of method overloading. You'll create multiple versions of calculation methods that handle different scenarios - from simple two-number operations to more complex calculations - all sharing the same intuitive method names.
You'll organize your code across two files:
Calculator.cs: Create aCalculatorclass in theMathToolsnamespace with overloaded methods that share names but accept different parameters:Multiply- Create three overloaded versions:- One that takes two
intparameters and returns their product as anint - One that takes three
intparameters and returns their product as anint - One that takes two
doubleparameters and returns their product as adouble
- One that takes two
Describe- Create two overloaded versions:- One that takes an
intand returns"Integer: {value}" - One that takes a
doubleand returns"Double: {value}"
- One that takes an
Program.cs: In your main file, create aCalculatorinstance and demonstrate how the compiler automatically selects the correct overloaded method based on the arguments you provide.
You will receive four inputs:
- First integer (e.g.,
5) - Second integer (e.g.,
4) - Third integer (e.g.,
3) - A decimal number (e.g.,
2.5)
Using your calculator, perform these operations and print each result on its own line:
- Multiply the first two integers (uses the two-int version)
- Multiply all three integers (uses the three-int version)
- Multiply the first integer and the decimal number (uses the two-double version)
- Describe the first integer (uses the int version)
- Describe the decimal number (uses the double version)
For example, if the inputs are 5, 4, 3, and 2.5, the output should be:
20
60
12.5
Integer: 5
Double: 2.5Notice how you call Multiply and Describe with different argument types and counts, yet the compiler knows exactly which version to use each time. This is compile-time polymorphism in action - the decision happens when your code is compiled, not when it runs!
Cheat sheet
Method overloading allows you to define multiple methods with the same name but different parameter lists. The compiler determines which version to call based on the arguments provided.
Each overloaded method must have a unique signature - either a different number of parameters or different parameter types:
public static void Print(string message)
{
Console.WriteLine(message);
}
public static void Print(string message, int times)
{
for (int i = 0; i < times; i++)
Console.WriteLine(message);
}
public static void Print(int number)
{
Console.WriteLine(number);
}
// The compiler picks the right version
Print("Hello"); // Calls Print(string)
Print("Hi", 3); // Calls Print(string, int)
Print(42); // Calls Print(int)Key points about method overloading:
- Overloading differs from optional parameters - with overloading, you have separate methods that can contain completely different logic for each case
- Return type alone doesn't make methods unique - the parameter list must be different
- Method overloading is a form of compile-time polymorphism, where the decision about which method to call is made when the code is compiled, not when it runs
Try it yourself
using System;
using MathTools;
class Program
{
public static void Main(string[] args)
{
// Read inputs
int firstInt = Convert.ToInt32(Console.ReadLine());
int secondInt = Convert.ToInt32(Console.ReadLine());
int thirdInt = Convert.ToInt32(Console.ReadLine());
double decimalNum = Convert.ToDouble(Console.ReadLine());
// TODO: Create a Calculator instance
// TODO: Call Multiply with two integers and print the result
// TODO: Call Multiply with three integers and print the result
// TODO: Call Multiply with the first integer and decimal number, print the result
// TODO: Call Describe with the first integer and print the result
// TODO: Call Describe with the decimal number and print the result
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator