In C#, how do you pass only a buffer size to `Export(string path, bool overwrite = false, int bufferSize = 4096)`, and which calls fail?
answer
- skip by name, not by comma
- optional parameters come last
- defaults must be constants
- named in its own position
- written order of evaluation
basics
~20 sA 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 sOptional 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 linesExporter.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
Recall how to skip an optional parameter with a named argument, and that optional parameters must come after required ones.
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.
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.
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.