Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 182 ยท Methods

Optional and Named Arguments

Learn C# optional parameters with default values, named arguments and their ordering rules, how overloads compete with defaults, and the CallerMemberName and CallerArgumentExpression attributes.

Many methods have a "normal" way to be called and a few knobs most callers never touch. File.ReadAllLines(path) is enough for most programs; sometimes you also want a specific encoding. Writing one overload for every combination quickly turns into a mess. C# gives you two features that work together to avoid that: optional parameters (parameters with a default value) and named arguments (naming the parameter you are filling in at the call).

Used well, they make calls shorter and more readable: CreateUser("ada", isAdmin: true) says more than CreateUser("ada", true, false, null). Used carelessly they cause real bugs, including defaults that are frozen into other people's compiled code. This lesson shows the rules, the traps, and the caller info attributes that let a method learn who called it. It continues from Methods and Parameters: ref, out, in and params.

Optional parameters

Give a parameter a default value with = value in the declaration. Callers can leave that argument out, and the compiler fills in the default for them.

C# Default values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The rules for defaults:

  • A default must be a compile-time constant: a literal, a const, default, null, an enum member, or new() for a struct. DateTime.Now, new List<int>() and other runtime expressions are not allowed.
  • Optional parameters must come after all required parameters. void M(int a = 1, int b) does not compile (error CS1737).
  • params must be last, after any optional parameters.
  • ref and out parameters cannot have default values.

When you need a "default" that is not a constant (a new list, the current time), use null as the marker and create the real value inside the method:

C# A non-constant default via null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Named arguments

At the call site, write parameterName: value to say which parameter you mean. Named arguments can appear in any order, and they let you skip optional parameters in the middle without supplying their defaults:

C# Named arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The most valuable use is clearing up boolean and numeric arguments: Resize(img, 100, 200, true) hides what true means, while Resize(img, width: 100, height: 200, keepAspect: true) documents itself. Many teams make this a style rule: name every literal true, false, null or magic number passed to a method.

Ordering rules

  1. Positional arguments always come first, matched to parameters left to right.
  2. Named arguments may follow in any order, provided each parameter is supplied only once.
  3. Since C# 7.2 a named argument may also sit in its own position before the positional ones (the Greeting(name: "Linus", "Howdy") call above).
  4. Every required parameter must receive a value, either positionally or by name.

Break a rule and the compiler tells you exactly which one:

C# Breaking the ordering rules (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The three calls produce three different errors: error CS1744: Named argument 'name' specifies a parameter for which a positional argument has already been given, error CS7036: There is no argument given that corresponds to the required parameter 'name' of 'Greeting(string, string)' and error CS1739: The best overload for 'Greeting' does not have a parameter named 'phrasee'. A typo in a parameter name is therefore caught at compile time, which is one more benefit of naming arguments.

Optional parameters versus overloads

Optional parameters and overloads can solve the same problem, and they can collide. When both an overload with fewer parameters and one with a default fit a call, C# prefers the candidate for which no default value had to be substituted.

C# Which overload wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that Print(1) picks Print(int): both overloads can take one int, but the first needs no default. This is a trap when you add an optional parameter to a method that already has a shorter overload, because the shorter one silently stays preferred. In your own APIs, avoid defining both for the same operation. Pick one style.

Defaults are copied into the caller at compile time. If library A has void Save(bool backup = true) and your program calls Save(), the compiler writes Save(true) into your compiled code. When A changes the default to false and ships a new version, your old compiled program still passes true until you recompile it. For public library APIs prefer overloads, or null as the "use the current default" signal. Inside one application that is compiled together, optional parameters are perfectly safe.

Optional parameters in the real world

A few guidelines from practice:

  • Use defaults for genuinely optional behavior with an obvious default: Take(int count = 10), a timeout, a separator, a culture.
  • Put the most important parameters first and the "tuning knobs" last. Callers should rarely need to name more than one or two.
  • When a method gets more than four or five optional parameters, switch to an options object (a record with init properties) and a single parameter. It reads like named arguments, is easy to extend without breaking callers, and can have a sensible default instance.
  • CancellationToken cancellationToken = default is a standard, popular optional parameter for async APIs; it is a constant (default), so it is allowed.
C# Options object instead of many optionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Caller info attributes

Some optional parameters are special. If you decorate one with a caller info attribute, the compiler fills in the default not with a constant but with information about the call site. These attributes live in System.Runtime.CompilerServices:

Attribute The compiler supplies
[CallerMemberName] the name of the method or property that made the call
[CallerLineNumber] the line number of the call in the source file
[CallerFilePath] the full path of the source file at compile time
[CallerArgumentExpression("param")] the exact source text of the argument passed for the parameter named param

The parameter must be optional, of a suitable type (string for names and paths, int for line numbers), and the caller normally just doesn't pass it. This is how logging helpers, argument checks and INotifyPropertyChanged implementations avoid hard-coded strings that go stale when you rename things.

C# Caller info attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first Log call comes from top-level statements, so the caller name is the compiler-generated entry point, <Main>$; the second call, made inside Worker.Run, reports Run. CallerArgumentExpression is the reason modern .NET exceptions such as ArgumentNullException.ThrowIfNull(user) can report Parameter 'user' without you typing the name. It was added in C# 10.

One security note: [CallerFilePath] embeds a path from the build machine into your compiled program. That is fine for diagnostics but is a minor information leak, and the value is meaningless on any other computer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which default value is NOT allowed for an optional parameter?

    Defaults must be compile-time constants. DateTime.Now is evaluated at run time, so take a nullable parameter and fill it in inside the method.
  2. 2. Given string Greeting(string name, string phrase = "Hello", int exclamations = 1), which call skips phrase and sets exclamations to 3?

    C# has no empty-argument syntax. A named argument lets you skip the optional parameters in between and keep their defaults.
  3. 3. Why can changing a default value in a library cause surprises for programs that already use it?

    The compiler copies the default value into each call site. A newly shipped library does not change already-compiled callers.
  4. 4. What does [CallerArgumentExpression("condition")] supply?

    The attribute fills in the exact text the caller wrote for that argument, which is great for assertions and argument validation messages.
  5. 5. A method has Print(int a) and Print(int a, int b = 0). Which one does Print(1) call?

    When two candidates fit equally well, C# prefers the one that needs no default values substituted, so the shorter overload wins.

Summary

  • = constant after a parameter makes it optional. Defaults must be compile-time constants and optional parameters come after required ones.
  • Named arguments (name: value) can appear in any order, skip optional parameters, and make calls with booleans or numbers readable. Positional arguments come first unless a named one is in its own position.
  • Misspelled or duplicated names are compile errors (CS1739, CS1744), so naming arguments also catches mistakes.
  • A candidate that needs no defaults beats one that does. Avoid mixing overloads and optional parameters for the same operation.
  • Defaults are baked into the compiled caller; in public libraries, prefer overloads or null-as-default.
  • For many knobs, use an options record. For non-constant defaults, use null and fill in inside the method.
  • [CallerMemberName], [CallerLineNumber], [CallerFilePath] and [CallerArgumentExpression] let the compiler pass call-site information automatically.

Next: Expression-Bodied Members and Local Functions