skip to content

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%

answer

  1. decided when the caller compiles
  2. the declaration the call binds to
  3. dispatch picks the body only
  4. explicit implementations ignore defaults
  5. names follow the same rule

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.

solid answer

~50 s

Two decisions happen at different times. When the caller is **compiled**, the compiler binds `x.Export("q3.csv")` to a declaration found through the static type of `x` and fills in the omitted argument from that declaration: `false` through `IExporter` or an abstract base, `true` through `CsvExporter`. When the call **runs**, interface or virtual dispatch chooses the method body, which is `CsvExporter`'s in every case. So one object behaves differently depending on how it is referenced, and the compiler does not warn when the defaults differ. Parameter names work the same way: named arguments must use the names of the bound declaration. An explicit interface implementation's default is ignored with warning CS1066, and an implementation that drops the default makes the argument required through the class (CS7036). The safe rule is identical defaults everywhere, or defaults only on one non-virtual entry point.

code

csharp · 23 lines
csharp
CsvExporter csv = new();
IExporter viaInterface = csv;
ExporterBase viaBase = csv;

csv.Export("q3.csv");
viaInterface.Export("q3.csv");
viaBase.Export("q3.csv");

interface IExporter
{
    void Export(string path, bool overwrite = false);
}

abstract class ExporterBase : IExporter
{
    public abstract void Export(string path, bool overwrite = false);
}

sealed class CsvExporter : ExporterBase
{
    public override void Export(string path, bool overwrite = true) =>
        Console.WriteLine($"CsvExporter.Export({path}, overwrite: {overwrite})");
}

go deeper

for a junior

Recall that a default value is filled in by the compiler at the call, not by the method when it runs.

for a middle

Explain how the static type picks the declaration whose default and parameter names a call uses, while dispatch picks only the body.

for a senior

Diagnose a behaviour difference between tests typed against a class and production code typed against an interface, and know CS1066 and CS7036 in this setting.

for a principal

Set a team rule for defaults in hierarchies, such as one non-virtual entry point with defaults over a virtual core, and enforce it in review.

## Two decisions, made at two different times An export pipeline often reaches the same object through different variables: a dependency container hands out `IExporter`, a test holds the concrete `CsvExporter`, and a shared base class sits in between. Consider: ```csharp interface IExporter { void Export(string path, bool overwrite = false); } abstract class ExporterBase : IExporter { public abstract void Export(string path, bool overwrite = false); } sealed class CsvExporter : ExporterBase { public override void Export(string path, bool overwrite = true) { /* ... */ } } ``` A call such as `x.Export("q3.csv")` involves two separate decisions: 1. **Compile time: binding.** The compiler looks up `Export` through the **static type** of `x`, which is the type the variable is declared with. It picks a declaration, checks the arguments against that declaration's parameters and fills every omitted optional argument with the default **written on that declaration**. The value becomes an ordinary argument in the caller's compiled code. 2. **Run time: dispatch.** Because `Export` is an interface member and a virtual method, the runtime looks at the **actual object** and runs the most derived implementation, which is `CsvExporter.Export`. The default is chosen in step 1; the body is chosen in step 2. Nothing in step 2 revisits the arguments. ## One object, three variables Running the code with the .NET 10 SDK: | Static type of the variable | Declaration bound | `overwrite` passed | Body that runs | |---|---|---|---| | `CsvExporter` | the override | `true` | `CsvExporter.Export` | | `IExporter` | the interface member | `false` | `CsvExporter.Export` | | `ExporterBase` | the abstract method | `false` | `CsvExporter.Export` | The compiler gives **no warning** for an override or implicit implementation whose default differs from the base or interface. The mismatch is legal, which is why it survives code review so easily. It also makes tests misleading: a unit test that constructs `CsvExporter` directly exercises the `true` default, while production code that receives an `IExporter` from a dependency container exercises `false`. Both run the same body, so coverage reports look identical. ## Related cases the compiler does flag - **Explicit interface implementation.** `void IExporter.Export(string path, bool overwrite = true)` can only be called through the interface, so its own default can never be used. The compiler reports warning CS1066, "The default value specified for parameter 'overwrite' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments". - **An implementation without the default.** If `CsvExporter` declares `Export(string path, bool overwrite)` with no default, calling `csv.Export("q3.csv")` through a `CsvExporter` variable is error CS7036, "There is no argument given that corresponds to the required parameter 'overwrite' of 'CsvExporter.Export(string, bool)'". Through `IExporter` or `ExporterBase` the same call still compiles. - **Renamed parameters.** If the override calls its parameter `replace`, then `csv.Export("a", replace: true)` compiles, `csv.Export("a", overwrite: true)` is CS1739, and through the base type only `overwrite:` works. Named arguments, like defaults, come from the bound declaration. ## Why the language works this way In an ordinary compiled call, optional arguments are resolved entirely by the compiler. By the time a virtual call executes, the call site has already pushed a complete argument list. Dispatch on the receiver therefore cannot change the arguments. The same compile-time nature explains why changing a default in a library has no effect on already-compiled callers, which is covered in the question on library versioning. ## Keeping a hierarchy safe - **Repeat identical defaults** on the interface, the base and every override, or put none on overrides at all and accept that callers using the concrete type must pass the value. - **Prefer one non-virtual entry point** that carries the defaults and calls a `protected abstract` or `virtual` core method with no defaults. The .NET design guidelines recommend the same shape for overloads: only the longest overload is virtual. - **Never put defaults on explicit implementations**; treat CS1066 as a bug. - **Document the default on the interface**, because in a codebase built on dependency injection that is the declaration most callers bind to. - **Review defaults in pull requests** that touch an interface, because tests typed against the concrete class can pass while production code typed against the interface behaves differently.

  • What does the C# compiler report when an explicit interface implementation declares its own default value?
    Warning CS1066: the default "will have no effect because it applies to a member that is used in contexts that do not allow optional arguments". An explicit implementation is reachable only through the interface, so calls always bind to the interface member and use its default.
  • If CsvExporter's override drops the default and declares Export(string path, bool overwrite), what happens to csv.Export("q3.csv")?
    Through a `CsvExporter` variable it no longer compiles: error CS7036, no argument for the required parameter `overwrite`, because the bound declaration is the override. Through `ExporterBase` or `IExporter` the call still compiles and passes the base's default, `false`.

  • Virtual dispatch also chooses the override's default value at run time.
  • The interface's default is ignored once a class implements the method.
  • An override whose default differs from the base's is a compile error.
  • Named arguments use the parameter names of the object's runtime type.