Letβs break down optional and named parameters in C# β very useful features for making methods more flexible and readable.
π 1. Optional Parameters
Optional parameters allow you to omit arguments when calling a method. You provide a default value in the method declaration.
Syntax
[access_modifier] void MethodName(type param1 = defaultValue, type param2 = defaultValue)
Example
public void Greet(string name = "Guest", string message = "Welcome!")
{
Console.WriteLine($"{message}, {name}!");
}
// Usage
Greet(); // Welcome!, Guest!
Greet("Alice"); // Welcome!, Alice!
Greet("Bob", "Hello"); // Hello, Bob!
-
Default values are used if arguments are not provided.
-
Optional parameters must come after required parameters in the method signature.
π 2. Named Parameters
Named parameters let you specify arguments by name, instead of relying on their order. They are only used when calling the Method, not whilst defining it.
Syntax
MethodName(paramName: value, otherParamName: value);
Example
public void DisplayInfo(string name, int age, string city)
{
Console.WriteLine($"{name}, {age} years old, lives in {city}");
}
// Using named parameters
DisplayInfo(age: 25, name: "Alice", city: "New York");
// Alice, 25 years old, lives in New York
-
Improves readability, especially with many parameters.
-
Can be combined with optional parameters.
π 3. Optional + Named Parameters Together
public void ShowOrder(string item = "Coffee", int quantity = 1, bool takeAway = false)
{
Console.WriteLine($"{quantity} {item}(s), TakeAway: {takeAway}");
}
// Call using named parameters
ShowOrder(quantity: 3, item: "Tea"); // 3 Tea(s), TakeAway: False
ShowOrder(takeAway: true); // 1 Coffee(s), TakeAway: True
ShowOrder(); // 1 Coffee(s), TakeAway: False
-
You can skip optional parameters by using named arguments.
-
Great for methods with many optional parameters.
π 4. Rules & Tips
- Optional parameters must be after required parameters in the declaration.
void Foo(int a, int b = 5) { } // β
void Foo(int a = 5, int b) { } // β Not allowed
-
Named parameters can be used in any order.
-
Combining optional + named parameters improves clarity.
-
Avoid overusing optional parameters if it reduces method clarity β sometimes overloading is better.
π 5. Summary Table
Feature | Syntax / Example | Notes |
---|---|---|
Optional Parameter | void Foo(int x = 10) | Default used if argument omitted |
Named Parameter | Foo(y: 5, x: 10) | Pass arguments in any order |
Combine Optional + Named | Foo(x: 3) | Skips other optional arguments |
Rules | Optional must follow required parameters | Named args can be used freely |
β Tip:
-
Optional & named parameters make your API flexible and readable, especially for utility and library methods.
-
Commonly used in
Console.WriteLine
, where many overloads exist.