C# Method Overloading
Method overloading means several methods share one name. The compiler picks a method by the types and count of its arguments.
Plus with whole numbers
This Plus method takes two int values. The call returns the int sum.
using System;
class Program
{
static int Plus(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Console.WriteLine(Plus(4, 5));
}
}Plus with decimal numbers
This Plus method takes two double values. The same name now works with decimal numbers.
using System;
class Program
{
static int Plus(int a, int b)
{
return a + b;
}
static double Plus(double a, double b)
{
return a + b;
}
static void Main(string[] args)
{
Console.WriteLine(Plus(2.5, 3.0));
}
}Different parameter counts
One Plus method takes two values and one takes three values. The compiler picks by how many arguments the call passes.
using System;
class Program
{
static int Plus(int a, int b)
{
return a + b;
}
static int Plus(int a, int b, int c)
{
return a + b + c;
}
static void Main(string[] args)
{
Console.WriteLine(Plus(6, 6));
Console.WriteLine(Plus(10, 20, 30));
}
}Example
using System;
class Program
{
static void Print(int number)
{
Console.WriteLine("Number: " + number);
}
static void Print(string text)
{
Console.WriteLine("Text: " + text);
}
static void Print(double value)
{
Console.WriteLine("Value: " + value);
}
static void Main(string[] args)
{
Print(7);
Print("C#");
Print(2.5);
}
}Key points
- Overloaded methods share a name.
- Each overload has a different list of parameters.
- The parameter list can differ in type.
- The parameter list can differ in count.
- The compiler matches a call to one overload.
In this example, three Print methods share one name. The first call passes an int, so the int overload prints the Number line. The second call passes a string, so the string overload prints the Text line. The third call passes a double, so the double overload prints the Value line.
Note
Overloads cannot differ only by return type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
How does the compiler choose between overloaded methods?