10 minlesson

Method Overloading

Method Overloading

Method overloading allows you to create multiple methods with the same name but different parameters. This provides flexibility while keeping your API clean.

What is Overloading?

Multiple methods can have the same name if they have different:

  • Number of parameters
  • Types of parameters
  • Order of parameter types
csharp
1static void Print(string message)
2{
3 Console.WriteLine(message);
4}
5
6static void Print(int number)
7{
8 Console.WriteLine(number);
9}
10
11static void Print(string message, int times)
12{
13 for (int i = 0; i < times; i++)
14 {
15 Console.WriteLine(message);
16 }
17}
18
19// All three can be called with 'Print'
20Print("Hello"); // Calls first version
21Print(42); // Calls second version
22Print("Hi", 3); // Calls third version

Why Overloading?

Cleaner API

csharp
1// Without overloading - different names
2static int AddIntegers(int a, int b) => a + b;
3static double AddDoubles(double a, double b) => a + b;
4static string AddStrings(string a, string b) => a + b;
5
6// With overloading - same name, intuitive usage
7static int Add(int a, int b) => a + b;
8static double Add(double a, double b) => a + b;
9static string Add(string a, string b) => a + b;
10
11// Usage is cleaner
12int sum1 = Add(5, 3);
13double sum2 = Add(5.5, 3.2);
14string combined = Add("Hello, ", "World");

Flexible Input

csharp
1static void DisplayDate(DateTime date)
2{
3 Console.WriteLine(date.ToShortDateString());
4}
5
6static void DisplayDate(int year, int month, int day)
7{
8 DateTime date = new DateTime(year, month, day);
9 Console.WriteLine(date.ToShortDateString());
10}
11
12static void DisplayDate(string dateString)
13{
14 if (DateTime.TryParse(dateString, out DateTime date))
15 {
16 Console.WriteLine(date.ToShortDateString());
17 }
18}
19
20// All valid calls
21DisplayDate(DateTime.Now);
22DisplayDate(2024, 6, 15);
23DisplayDate("June 15, 2024");

Overloading Rules

Valid Overloads

csharp
1// Different number of parameters
2static void Log(string message) { }
3static void Log(string message, string category) { }
4static void Log(string message, string category, int level) { }
5
6// Different parameter types
7static void Process(int value) { }
8static void Process(string value) { }
9static void Process(double value) { }
10
11// Different parameter order
12static void Transfer(string from, int amount) { }
13static void Transfer(int amount, string to) { }

Invalid Overloads

csharp
1// Cannot differ only by return type
2static int Calculate(int x) => x * 2;
3// static double Calculate(int x) => x * 2.0; // Error!
4
5// Cannot differ only by parameter names
6static void Save(string name) { }
7// static void Save(string title) { } // Error! Same signature

Optional Parameters

Instead of overloading, you can use default values:

csharp
1static void Greet(string name, string greeting = "Hello", bool exclaim = true)
2{
3 string punctuation = exclaim ? "!" : ".";
4 Console.WriteLine($"{greeting}, {name}{punctuation}");
5}
6
7Greet("Alice"); // Hello, Alice!
8Greet("Bob", "Hi"); // Hi, Bob!
9Greet("Charlie", "Good day", false); // Good day, Charlie.

Rules for Optional Parameters

csharp
1// Optional parameters must come after required ones
2static void Example(int required, string optional = "default")
3{
4 // Valid
5}
6
7// static void Bad(string optional = "default", int required)
8// {
9// // Error! Required after optional
10// }

Named Arguments

Specify arguments by name for clarity:

csharp
1static void CreateUser(string name, int age, bool isAdmin = false)
2{
3 Console.WriteLine($"User: {name}, Age: {age}, Admin: {isAdmin}");
4}
5
6// Positional arguments
7CreateUser("Alice", 30, true);
8
9// Named arguments - order doesn't matter
10CreateUser(age: 25, name: "Bob");
11CreateUser(name: "Charlie", isAdmin: true, age: 35);
12
13// Mix of both
14CreateUser("Diana", age: 28);

Why Named Arguments?

csharp
1// Unclear what true means
2ProcessFile("data.txt", true, false, true);
3
4// Clear with named arguments
5ProcessFile("data.txt",
6 compress: true,
7 encrypt: false,
8 backup: true);

Combining Overloading and Defaults

Use overloading to call a main implementation:

csharp
1// Main implementation
2static void SendEmail(string to, string subject, string body, bool urgent)
3{
4 Console.WriteLine($"Sending{(urgent ? " URGENT" : "")} email to {to}");
5 Console.WriteLine($"Subject: {subject}");
6 Console.WriteLine($"Body: {body}");
7}
8
9// Overloaded versions call main
10static void SendEmail(string to, string subject, string body)
11{
12 SendEmail(to, subject, body, false); // Default not urgent
13}
14
15static void SendEmail(string to, string subject)
16{
17 SendEmail(to, subject, "", false); // Empty body
18}
19
20// Usage
21SendEmail("user@example.com", "Hello", "Welcome!", true);
22SendEmail("user@example.com", "Update", "New features available");
23SendEmail("user@example.com", "Newsletter");

Practical Example: Drawing Shapes

csharp
1// Draw with default character
2static void DrawLine(int length)
3{
4 DrawLine(length, '-');
5}
6
7// Draw with custom character
8static void DrawLine(int length, char c)
9{
10 Console.WriteLine(new string(c, length));
11}
12
13// Draw box with default character
14static void DrawBox(int width, int height)
15{
16 DrawBox(width, height, '*');
17}
18
19// Draw box with custom character
20static void DrawBox(int width, int height, char c)
21{
22 DrawLine(width, c);
23 for (int i = 0; i < height - 2; i++)
24 {
25 Console.Write(c);
26 Console.Write(new string(' ', width - 2));
27 Console.WriteLine(c);
28 }
29 DrawLine(width, c);
30}
31
32// Usage
33DrawLine(10); // ----------
34DrawLine(10, '='); // ==========
35DrawBox(8, 4); // Uses *
36DrawBox(8, 4, '#'); // Uses #

Summary

In this lesson, you learned:

  • Overloading: multiple methods with the same name, different parameters
  • Overloads must differ by parameter count, types, or order
  • Cannot overload by return type alone
  • Optional parameters provide default values
  • Named arguments improve readability
  • Combine overloading with defaults to reduce code duplication

Next, we'll learn about expression-bodied methods.