skip to content

Defaults, Names and Params

Optional parameter defaults are compiled into callers, named arguments reorder calls, and params now takes spans and lists. Interviewers ask why changing a default changed nothing.

on this pageshow

explore

questions

6

In C#, how do you pass only a buffer size to `Export(string path, bool overwrite = false, int bufferSize = 4096)`, and which calls fail?

level: juniorimportance: must knowfreq 72%

answer

  1. skip by name, not by comma
  2. optional parameters come last
  3. defaults must be constants
  4. named in its own position
  5. written order of evaluation

basics

~20 s

A named argument skips the gap: Export("q3.csv", bufferSize: 8192) leaves overwrite at false. The compiler rejects an empty comma slot (CS0839), an out-of-position named argument followed by a positional one (CS8323), and unknown or repeated names.

solid answer

~40 s

Optional parameters must follow every required one (CS1737 otherwise), and each default must be a compile-time constant, `new S()` or `default(S)` for a value type, or `null` (CS1736 otherwise). To skip `overwrite`, name what you pass: `Export("q3.csv", bufferSize: 8192)`. C# has no empty argument slots, so `Export("q3.csv", , 8192)` is CS0839. Since C# 7.2 a named argument may be followed by positional ones only when it sits in its own position: `Export(path: "q3.csv", true)` compiles, `Export(overwrite: true, "q3.csv")` is CS8323. A name the method does not have is CS1739, the same name twice is CS1740, and naming a parameter already filled by position is CS1744. Arguments are evaluated in the order they are written, not in parameter order.

code

csharp · 16 lines
csharp
Exporter.Export("q3.csv");
Exporter.Export("q3.csv", bufferSize: 8192);
Exporter.Export(path: "q3.csv", true);
Exporter.Export(bufferSize: Next("bufferSize", 8192), path: Next("path", "q3.csv"));

static T Next<T>(string label, T value)
{
    Console.WriteLine($"evaluating {label}");
    return value;
}

static class Exporter
{
    public static void Export(string path, bool overwrite = false, int bufferSize = 4096) =>
        Console.WriteLine($"Export({path}, overwrite: {overwrite}, bufferSize: {bufferSize})");
}

go deeper

for a junior

Recall how to skip an optional parameter with a named argument, and that optional parameters must come after required ones.

for a middle

Explain what may serve as a default value, the C# 7.2 rule for named arguments in position, and the written-order evaluation of arguments.

for a senior

Show that you treat public parameter names as part of a library's source contract, and use named arguments to make adjacent bool or int arguments unambiguous in reviews.

for a principal

Be ready to argue when a team's coding standard should require named arguments, such as for boolean flags, and when that adds noise without preventing bugs.

## Optional parameters: what the declaration may say An **optional parameter** is a parameter declared with a default value: `bool overwrite = false`. A caller may leave it out, and the compiler then supplies the default. The **required parameters** are the ones without a default; a call must supply every one of them. Take a reporting library's method: ```csharp public static void Export(string path, bool overwrite = false, int bufferSize = 4096) ``` The compiler enforces a few rules on such a declaration, each with its own diagnostic: - **Optional parameters come last.** `void Log(int level = 1, string text)` is error CS1737, "Optional parameters must appear after all required parameters". A `params` parameter may still follow the optional ones. - **A default must be fixed at compile time.** It can be a constant (`4096`, `"csv"`, an enum member), `null`, `default`, `default(S)` or `new S()` for a value type `S`. `DateTime when = DateTime.Now` and `List<string> names = new List<string>()` are both CS1736, "Default parameter value for 'names' must be a compile-time constant". - **Reference types other than `string` take only `null`.** `object tag = 5` is CS1763: "A default parameter value of a reference type other than string can only be initialized with null". ## Skipping a parameter with a named argument A **named argument** is written `parameterName: value` and binds to a parameter by its name instead of its position. That is the only way to supply a later optional parameter while leaving an earlier one at its default: | Call | Result | |---|---| | `Export("q3.csv")` | `overwrite` false, `bufferSize` 4096 | | `Export("q3.csv", bufferSize: 8192)` | `overwrite` stays false, `bufferSize` 8192 | | `Export("q3.csv", , 8192)` | error CS0839, "Argument missing" | | `Export("q3.csv", size: 8192)` | error CS1739, no parameter named `size` | C# has no empty comma slots. Named arguments work the same way for constructors, indexers and delegate invocations, so a constructor call such as `new ReportWriter(path, bufferSize: 8192)` follows the same rules. Named arguments also work for required parameters, which is often worth doing purely for readability when two adjacent parameters share a type, such as two `bool` flags. ## Mixing named and positional arguments Arguments without names are **positional**: the first fills the first parameter, and so on. The rules for mixing the two forms changed once: 1. Before C# 7.2, every named argument had to come after all positional ones. The C# 7.1 compiler reports CS1738, "Named argument specifications must appear after all fixed arguments have been specified". 2. Since C# 7.2, a named argument may be followed by positional ones **if it sits in its own position**. `Export(path: "q3.csv", true)` compiles: `path` is the first argument and the first parameter, so `true` still binds to `overwrite`. 3. A named argument **out of its position** cannot be followed by a positional one: `Export(overwrite: true, "q3.csv")` is CS8323, "Named argument 'overwrite' is used out-of-position but is followed by an unnamed argument". Two more mistakes have their own errors. Naming a parameter that a positional argument already filled, as in `Export("q3.csv", path: "x.csv")`, is CS1744. Naming the same parameter twice is CS1740. ## The order the arguments run in Named arguments change which parameter receives a value, not when the value is computed. The compiler evaluates arguments **in the order they are written**. In `Export(bufferSize: Next(), path: Name())`, `Next()` runs before `Name()` even though `path` is the first parameter. This matters when argument expressions have side effects such as logging, reading a stream or incrementing a counter. ## Parameter names become part of the contract Once callers write `bufferSize: 8192`, the parameter's name is something they depend on. Renaming `bufferSize` to `size` in the library makes those callers fail with CS1739 the next time they compile. Callers that were already compiled keep working, because a compiled call refers to the method by its parameter types, not by its parameter names. ## What a strong answer covers - Skip optional parameters by naming the next one you pass; never expect a gap to work. - State the placement rule for optional parameters and what may serve as a default. - Know that C# 7.2 relaxed the old rule, and that the remaining restriction is about position. - Know the evaluation order, and that renaming a public parameter is a source-breaking change.

  • Can a C# default parameter value be DateTime.Now or a new List<string>(), and what do you write instead?
    No. A default must be a constant, `null`, `default`, or `new S()`/`default(S)` for a value type, so both are CS1736. Declare `DateTime? when = null` or `List<string>? names = null` and compute the real value inside the method, for example `when ??= DateTime.Now;`, so it is evaluated on each call.
  • In which order are the arguments of Export(bufferSize: Next(), path: Name()) evaluated?
    Left to right as written: `Next()` runs before `Name()`, even though `path` is the first parameter. Naming changes which parameter receives each value, never the order in which the argument expressions run, so side effects happen in the order a reader sees them.
  • Why can renaming a parameter in a library break callers that compiled fine before?
    Callers that pass that argument by name, such as `bufferSize: 8192`, get CS1739 when they recompile against the renamed version. Already-compiled callers keep running, because a compiled call refers to the method by its parameter types, not its names. So a public parameter name is part of the source contract.

  • Leaving an empty slot such as Export("q3.csv", , 8192) skips a parameter.
  • A named argument can never be followed by a positional one.
  • Optional parameters can be declared anywhere in the parameter list.
  • A default can be any expression, such as DateTime.Now, evaluated on each call.
  • Named arguments are evaluated in parameter order, not in written order.
open as a page

A C# reporting library's v2 changes `Export`'s default `bufferSize` from 4096 to 81920; why does an app compiled against v1 still pass 4096 after the DLL is upgraded?

level: seniorimportance: must knowfreq 48%

basics

~20 s

The C# compiler copies an optional parameter's default into each call site when the caller is compiled, so the app's IL still contains the literal 4096. Only rebuilding the app against v2 picks up 81920.

open as a page

In C#, what does a `params string?[]? names` parameter receive for `Describe()`, `Describe(null)`, `Describe((string?)null)` and an existing array?

level: middleimportance: should knowfreq 52%

basics

~10 s

Describe() gets an empty array (the shared Array.Empty<string?>() instance), Describe(null) gets a null array, Describe((string?)null) gets a one-element array holding null, and an existing array is passed as is, so writes reach the caller.

open as a page

Since C# 13, what does the compiler build for calls to `params ReadOnlySpan<int>`, `params IEnumerable<int>` and `params List<int>` parameters, and what does each cost?

level: middleimportance: should knowfreq 35%

basics

~20 s

Since C# 13, params ReadOnlySpan<int> gets a span over a buffer on the caller's stack, so no heap allocation; params IEnumerable<int> gets a compiler-generated read-only collection; params List<int> gets a new List<int> filled with Add.

open as a page

In C#, `IExporter` declares `Export(string path, bool overwrite = false)` and `CsvExporter` implements it with `overwrite = true`; why does `Export("q3.csv")` depend on the variable's type?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The compiler copies a default into the call from the declaration it binds to, which depends on the variable's static type: IExporter says false, CsvExporter says true. At run time CsvExporter's body runs either way, with whichever value the call passed.

open as a page

For a public C# library on NuGet, should `Export` grow through optional parameters or overloads, and how do you add a parameter in v2 without breaking compiled callers?

level: principalimportance: should knowfreq 30%

basics

~20 s

Appending an optional parameter keeps source compatibility but removes the old signature, so compiled callers hit MissingMethodException. Keep the v1 signature as an overload without defaults that forwards to the new method, and put defaults on one longest overload only.

open as a page