C# provides two distinct parameter features that enhance code readability and flexibility: named parameters and optional parameters.
Named Parameters
Named parameters allow you to specify arguments by their parameter name when calling a method, instead of relying on posisional order. This makes the caller's intent clearer and lets you skip parameters that have default values.
void ShowUser(string firstName, string lastName, int age)
{
Console.WriteLine($"User: {firstName} {lastName}, Age: {age}");
}
// Call using named arguments (order does not matter)
ShowUser(lastName: "Doe", firstName: "Jane", age: 28);
By naming each argument, the code becomes self-documenting. However, all required parameters must still be provided. The following call would cause a compilation error because firstName and age are not optional:
ShowUser(lastName: "Doe"); // Error: missing 'firstName' and 'age'
Named parameter are especially useful when a method has many parameters of the same type, or when you want to pass only a subset of parameters.
Optional Parameters
Optional parameters let you define default values in the method signature, so callers can omit those arguments. The default is used when the argument is not supplied.
void ShowUser(string firstName, string lastName, int age = 25)
{
Console.WriteLine($"User: {firstName} {lastName}, Age: {age}");
}
// Uses default age (25)
ShowUser("Jane", "Doe");
// Overrides default age
ShowUser("John", "Smith", 30);
Optional parameters must appear after all required parameters in the signature. They cannot be declared with ref or out modifiers.
// Compilation error: optional parameter cannot be 'ref'
void ShowUser(string firstName, string lastName, ref int age = 25) { }
Practical Examples
Named Parameters in Action
When a method has many parameters and you only need a few, named parameters improve clarity:
void CreateProfile(int id, string name, string email, string city = "New York")
{
// implementation
}
// Only set id and name, skip email and city
CreateProfile(id: 101, name: "Alice");
Optional Parameters in Action
For methods where common defaults exist, optional parameters reduce boilerplate:
void OpenWindow(int width = 800, int height = 600)
{
Console.WriteLine($"Window opened: {width}x{height}");
}
// All variations work
OpenWindow();
OpenWindow(width: 1024);
OpenWindow(width: 1024, height: 768);
Another typical use is logging, where the timestamp defaults to the current time:
void LogMessage(string message, DateTime? timestamp = null)
{
DateTime ts = timestamp ?? DateTime.Now;
Console.WriteLine($"[{ts:yyyy-MM-dd HH:mm:ss}] {message}");
}
LogMessage("Application started");
LogMessage("Error occurred", new DateTime(2023, 12, 1, 10, 30, 0));
Both features can be combined, alllowing callers to pass arguments by name while skipping optional ones. This combination leads to more expressive and maintainable code, especially in APIs with many parameters or frequently used defaults.