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

  1. 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
  1. Named parameters can be used in any order.

  2. Combining optional + named parameters improves clarity.

  3. Avoid overusing optional parameters if it reduces method clarity β€” sometimes overloading is better.


πŸ“Œ 5. Summary Table

FeatureSyntax / ExampleNotes
Optional Parametervoid Foo(int x = 10)Default used if argument omitted
Named ParameterFoo(y: 5, x: 10)Pass arguments in any order
Combine Optional + NamedFoo(x: 3)Skips other optional arguments
RulesOptional must follow required parametersNamed 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.