C#
Method overloading
Learn to define same-named methods with different parameters.
Method overloading
In C# you can define multiple methods with the same name; this is called overloading. The only rule is that the parameters must differ in number or type. The compiler picks the best overload by looking at the arguments in the call.
Example: static int Add(int a, int b) and static int Add(int a, int b, int c) are two overloads. Add(2, 3) calls the first, Add(1, 2, 3) calls the second.
Overload resolution
The compiler looks at the number and types of arguments in the call and picks the best overload. If there is an exact match, it prefers that; otherwise it looks for the closest candidate that involves a type conversion. If it is ambiguous, a compile error is raised.
The signature is the method name plus the ordered list of parameter types; the return type is not part of the signature. Two overloads that differ only in the return type cannot be defined.
Exercise Two- and three-parameter Add
Define two overloads: static int Add(int a, int b) { return a + b; } and static int Add(int a, int b, int c) { return a + b + c; }. In Main, call Add(1, 2, 3) and print the result with Console.WriteLine.
Show example solution
Write the two static int Add definitions, add Console.WriteLine(Add(1, 2, 3)); in Main.
Example solution:
using System;
class Program
{
// Define two- and three-parameter Add overloads
static int Add(int a, int b) { return a + b; }
static int Add(int a, int b, int c) { return a + b + c; }
static void Main()
{
// Sum three numbers and print
Console.WriteLine(Add(1, 2, 3));
}
}
Test yourself
-
What does Multiply(2, 3, 4) print?
static int Multiply(int a, int b) { return a * b; }
static int Multiply(int a, int b, int c) { return a * b * c; }
Console.WriteLine(Multiply(2, 3, 4));
Show answer
24 — Correct. The three-parameter overload is called; 2*3*4 = 24.
-
Two-parameter Multiply call
int result = ____;
Console.WriteLine(result);
Show answer
int result = Multiply(2, 3);
Console.WriteLine(result);
-
Match the overload signatures
- Add(int, int)
- Adds integers
- Add(double, double)
- Adds decimals
- Multiply(int, int, int)
- Multiplies three
- Multiply(int, int)
- Multiplies two
Next lesson: Local functions