Optional and Named Arguments
Giving parameters default values and calling methods with named arguments for clarity.
2 min read
Not every parameter needs a value on every call. C# lets you give parameters defaults, and lets callers name arguments explicitly for clarity.
Optional parameters
A parameter with a default value becomes optional:
static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Greet("Ada"); // "Hello, Ada!"
Greet("Ada", "Welcome"); // "Welcome, Ada!"Optional parameters must come after all required ones — you can't have a required parameter follow an optional one, since the compiler matches positionally by default:
// Invalid: required parameter can't follow an optional one
static void Greet(string greeting = "Hello", string name) { }Named arguments
Named arguments let you specify which parameter you're supplying by name, independent of position:
static void CreateUser(string name, int age, bool isAdmin = false)
{
Console.WriteLine($"{name}, {age}, admin={isAdmin}");
}
CreateUser(name: "Ada", age: 30, isAdmin: true);
CreateUser(age: 30, name: "Ada"); // order doesn't matter with named argumentsThis is especially valuable with several bool or same-typed parameters in a row, where a plain positional call like CreateUser("Ada", 30, true) forces the reader to go check the method signature just to know what true means. Compare:
// Unclear at the call site
ScheduleMeeting("Standup", true, false);
// Clear, self-documenting
ScheduleMeeting("Standup", isRecurring: true, sendReminder: false);Combining both
Named arguments also let you skip earlier optional parameters and only supply a later one:
static void Configure(int retries = 3, int timeoutMs = 1000, bool verbose = false)
{
// ...
}
Configure(verbose: true); // retries and timeoutMs keep their defaultsWithout named arguments, you'd have to repeat 3 and 1000 explicitly just to reach verbose. Together, optional and named arguments let a method support a wide range of call patterns without you having to write a pile of overloads to cover each combination.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.