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
csharp1static void Print(string message)2{3 Console.WriteLine(message);4}56static void Print(int number)7{8 Console.WriteLine(number);9}1011static void Print(string message, int times)12{13 for (int i = 0; i < times; i++)14 {15 Console.WriteLine(message);16 }17}1819// All three can be called with 'Print'20Print("Hello"); // Calls first version21Print(42); // Calls second version22Print("Hi", 3); // Calls third version
Why Overloading?
Cleaner API
csharp1// Without overloading - different names2static 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;56// With overloading - same name, intuitive usage7static 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;1011// Usage is cleaner12int sum1 = Add(5, 3);13double sum2 = Add(5.5, 3.2);14string combined = Add("Hello, ", "World");
Flexible Input
csharp1static void DisplayDate(DateTime date)2{3 Console.WriteLine(date.ToShortDateString());4}56static void DisplayDate(int year, int month, int day)7{8 DateTime date = new DateTime(year, month, day);9 Console.WriteLine(date.ToShortDateString());10}1112static void DisplayDate(string dateString)13{14 if (DateTime.TryParse(dateString, out DateTime date))15 {16 Console.WriteLine(date.ToShortDateString());17 }18}1920// All valid calls21DisplayDate(DateTime.Now);22DisplayDate(2024, 6, 15);23DisplayDate("June 15, 2024");
Overloading Rules
Valid Overloads
csharp1// Different number of parameters2static void Log(string message) { }3static void Log(string message, string category) { }4static void Log(string message, string category, int level) { }56// Different parameter types7static void Process(int value) { }8static void Process(string value) { }9static void Process(double value) { }1011// Different parameter order12static void Transfer(string from, int amount) { }13static void Transfer(int amount, string to) { }
Invalid Overloads
csharp1// Cannot differ only by return type2static int Calculate(int x) => x * 2;3// static double Calculate(int x) => x * 2.0; // Error!45// Cannot differ only by parameter names6static void Save(string name) { }7// static void Save(string title) { } // Error! Same signature
Optional Parameters
Instead of overloading, you can use default values:
csharp1static void Greet(string name, string greeting = "Hello", bool exclaim = true)2{3 string punctuation = exclaim ? "!" : ".";4 Console.WriteLine($"{greeting}, {name}{punctuation}");5}67Greet("Alice"); // Hello, Alice!8Greet("Bob", "Hi"); // Hi, Bob!9Greet("Charlie", "Good day", false); // Good day, Charlie.
Rules for Optional Parameters
csharp1// Optional parameters must come after required ones2static void Example(int required, string optional = "default")3{4 // Valid5}67// static void Bad(string optional = "default", int required)8// {9// // Error! Required after optional10// }
Named Arguments
Specify arguments by name for clarity:
csharp1static void CreateUser(string name, int age, bool isAdmin = false)2{3 Console.WriteLine($"User: {name}, Age: {age}, Admin: {isAdmin}");4}56// Positional arguments7CreateUser("Alice", 30, true);89// Named arguments - order doesn't matter10CreateUser(age: 25, name: "Bob");11CreateUser(name: "Charlie", isAdmin: true, age: 35);1213// Mix of both14CreateUser("Diana", age: 28);
Why Named Arguments?
csharp1// Unclear what true means2ProcessFile("data.txt", true, false, true);34// Clear with named arguments5ProcessFile("data.txt",6 compress: true,7 encrypt: false,8 backup: true);
Combining Overloading and Defaults
Use overloading to call a main implementation:
csharp1// Main implementation2static 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}89// Overloaded versions call main10static void SendEmail(string to, string subject, string body)11{12 SendEmail(to, subject, body, false); // Default not urgent13}1415static void SendEmail(string to, string subject)16{17 SendEmail(to, subject, "", false); // Empty body18}1920// Usage21SendEmail("user@example.com", "Hello", "Welcome!", true);22SendEmail("user@example.com", "Update", "New features available");23SendEmail("user@example.com", "Newsletter");
Practical Example: Drawing Shapes
csharp1// Draw with default character2static void DrawLine(int length)3{4 DrawLine(length, '-');5}67// Draw with custom character8static void DrawLine(int length, char c)9{10 Console.WriteLine(new string(c, length));11}1213// Draw box with default character14static void DrawBox(int width, int height)15{16 DrawBox(width, height, '*');17}1819// Draw box with custom character20static 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}3132// Usage33DrawLine(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.