Optional Parameters and Overloading
Optional Parameters and Method Overloading in C#
Default (optional) parameters A parameter with a default value is optional at the call site:
csharp
void Log(string message, string level = "INFO") { … }
Log("Started"); // level = "INFO"
Log("Failed", "ERROR"); // level = "ERROR"Default values must be compile-time constants or default(T).
Named arguments Call a method specifying argument names to improve clarity or skip optional parameters:
csharp
Log(message: "Done", level: "DEBUG");Method overloading Multiple methods with the same name but different parameter signatures:
csharp
int Add(int a, int b) { … }
double Add(double a, double b) { … }The compiler selects the best overload based on argument types.
Key points:
- Prefer optional parameters over many overloads for simple variations.
- Use overloads when the implementations differ significantly.
- Named arguments are self-documenting and reduce confusion with multiple booleans.
Code Examples
Optional parameters and named argumentscsharp
using System;
class Logger {
static void Log(string message, string level = "INFO", bool timestamp = false) {
string prefix = timestamp ? $"[{DateTime.Now:HH:mm:ss}] " : "";
Console.WriteLine($"{prefix}[{level}] {message}");
}
static void Main() {
Log("Server started");
Log("Disk full", "WARN");
Log("Crashed", level: "ERROR", timestamp: false);
}
}Named arguments let you skip to a specific optional parameter without supplying all preceding ones.
Method overloadingcsharp
using System;
class Converter {
public static string Format(int value) => $"int: {value}";
public static string Format(double value) => $"double: {value:F2}";
public static string Format(bool value) => $"bool: {(value ? "yes" : "no")}";
public static string Format(int value, int padWidth) => value.ToString().PadLeft(padWidth, '0');
static void Main() {
Console.WriteLine(Format(42));
Console.WriteLine(Format(3.14));
Console.WriteLine(Format(true));
Console.WriteLine(Format(7, 4));
}
}The compiler resolves the correct overload based on argument types at compile time.
Quick Quiz
1. Where must optional parameters appear in a method signature?
2. What are named arguments useful for?
Was this lesson helpful?