Optional Parameters and Named Arguments in C#

An optional parameter has a default value in the method declaration. Callers can leave it out, and the compiler fills in the default. Combined with named arguments, which let callers pass a value by parameter name, this removes the need for long chains of overloads. Both arrived in C# 4.0 and work the same way today.

Example

SendReport("sales.csv", 123);
SendReport("sales.csv", 123, format: "pdf");
SendReport("sales.csv", 123, "xlsx", compress: true);

static void SendReport(string file, int userId, string format = "csv", bool compress = false)
{
    Console.WriteLine($"{file} to user {userId} as {format}, compress: {compress}");
}

Output:

sales.csv to user 123 as csv, compress: False
sales.csv to user 123 as pdf, compress: False
sales.csv to user 123 as xlsx, compress: True

The second call skips nothing in the middle, so format: is optional there; it just makes the call easier to read. Named arguments become necessary when you want to set a later parameter and keep the default of an earlier one, as in SendReport("sales.csv", 123, compress: true).

The rules

Optional parameters come last. They must follow all required parameters. The one exception is a params array, which goes after them.

Defaults must be compile-time constants. That means a literal, a const, null, default, or new S() for a struct type. You cannot write DateTime when = DateTime.Now. The usual workaround is a nullable parameter with a null default:

static void Log(string message, DateTime? timestamp = null)
{
    DateTime when = timestamp ?? DateTime.UtcNow;
    Console.WriteLine($"{when:O} {message}");
}

Named arguments can go in any order, as long as they come after positional ones. Since C# 7.2 you may also name an argument that is in its correct position and then continue positionally, which is handy for documenting a bare true or null.

They work almost everywhere. Methods, constructors, indexers and delegates can all have optional parameters. Since C# 12, lambdas can too: var greet = (string name = "world") => $"Hello, {name}";.

The versioning trap

The default value is not looked up when the method runs. The compiler copies it into every call site. If a library ships format = "csv", and a later version changes it to format = "json", applications compiled against the old version keep passing "csv" until they are recompiled.

Adding a new optional parameter to a public method has a related problem: it changes the method’s signature. Code compiled against the old signature fails at run time with MissingMethodException, even though its source would still compile. For public library APIs, add an overload instead and keep the old signature around.

Inside a single application, where everything is compiled together, neither issue matters.

Overloads and optional parameters together

When an overload without the optional parameter exists, the compiler prefers it:

Printer.Print("a");   // calls Print(string)

static class Printer
{
    public static void Print(string text) => Console.WriteLine("one parameter");
    public static void Print(string text, int copies = 1) => Console.WriteLine("two parameters");
}

That call prints one parameter. Mixing the two styles like this tends to confuse readers, so pick one per method group.

A similar surprise comes from interfaces. If an interface method declares int retries = 3 and the class implementing it declares int retries = 5, the default you get depends on the static type of the variable you call through, not on the object. Keep defaults identical, or declare them only on the interface.

Caller information attributes

Some attributes rely on optional parameters to work. [CallerMemberName], [CallerFilePath], [CallerLineNumber] and [CallerArgumentExpression] tell the compiler to replace the default with information about the call site:

using System.Runtime.CompilerServices;

static void Trace(string message, [CallerMemberName] string caller = "")
{
    Console.WriteLine($"{caller}: {message}");
}

The "" default is never used in practice; the compiler always passes the name of the calling method. This is how INotifyPropertyChanged implementations avoid hard-coding property names.

Related examples

Leave a Comment