skip to content

In C#, a logger declares `Log(string message)`, `Log(string message, int level = 0)` and `Log(string format, params object[] args)`; which one does `Log("ready")` call, and why?

level: middleimportance: should knowfreq 38%

answer

  1. all three accept one string
  2. tie-breakers after the conversions
  3. normal form before expanded form
  4. no default value filled in

basics

~20 s

Log(string message) is called. All three accept the string equally well, so tie-breakers decide: a method usable without params expansion beats the params one, and one that needs no default value filled in beats Log(string, int = 0).

solid answer

~50 s

All three overloads are applicable: `Log(string)` directly, `Log(string, int = 0)` by filling in the default, and the `params` method in its **expanded form** with an empty array. The argument converts to `string` by identity in each, so the conversions cannot rank them, and C# falls back to **tie-breakers**. A method applicable in its **normal form** beats one applicable only in its expanded form, which removes the `params` overload. A method whose parameters all receive an argument beats one that needs a **default value substituted**, which removes `Log(string, int = 0)`. So `Log("ready")` calls `Log(string)`. The tie-breakers apply only when the conversions tie: `Log("ready", 2)` calls `Log(string, int)`, because `2` matches `int` by identity but must be boxed to `object` for the `params` array, and `Log("ready {0}", "disk")` reaches the `params` method because nothing else accepts a string second argument.

code

csharp · 12 lines
csharp
var log = new Logger();
log.Log("ready");                  // Log(string): no default filled, no params expansion
log.Log("ready", 2);               // Log(string, int): int is an identity match
log.Log("ready {0}", "disk");      // only the params overload accepts a string second argument
log.Log("ready {0} {1}", 1, 2);    // only the params overload accepts three arguments

class Logger
{
    public void Log(string message) => Console.WriteLine("Log(string)");
    public void Log(string message, int level = 0) => Console.WriteLine("Log(string, int = 0)");
    public void Log(string format, params object[] args) => Console.WriteLine($"Log(string, params object[]) with {args.Length}");
}

go deeper

for a junior

Recall that a call matching a method exactly is preferred over one that needs a default value filled in or a params array built.

for a middle

Explain the normal versus expanded form, the default-value tie-breaker, and that tie-breakers only run when the argument conversions tie.

for a senior

Review overload sets that differ by an optional or params tail, and check the short form does the same work, since it wins every tie.

for a principal

Keep convenience overloads few and distinct in a shared API, so that adding one later cannot quietly change which method existing calls reach.

## Three overloads that all accept one string A logging facade often grows overloads for convenience: ```csharp public void Log(string message) { } public void Log(string message, int level = 0) { } public void Log(string format, params object[] args) { } ``` A call `Log("ready")` passes one string, and every one of these can accept it: - `Log(string)` takes it directly; - `Log(string, int = 0)` takes it if the compiler fills in `level` from its **default value**; - `Log(string, params object[])` takes it in its **expanded form**, the form in which the compiler builds the `args` array from the remaining arguments; here that array is empty. Overload resolution first compares how well each argument converts to each candidate's parameter. Here the only argument is a `string` going to a `string` parameter in all three, an identity conversion each time, so that comparison ends in a tie. ## The tie-breakers When the parameter types that receive the arguments are the same for two candidates, the compiler applies a fixed list of **tie-breaking rules**. The ones that matter for logging overloads are these, in the order the C# 14 compiler applies them; the first one that separates two candidates decides: 1. A **non-generic** method beats a generic one. 2. A method applicable in its **normal form** beats one applicable only in its **expanded form**. 3. If both are applicable only in expanded form, the one with more declared parameters wins. 4. A method whose parameters **all have a corresponding argument** beats one that needs **a default value substituted** for at least one optional parameter. 5. A method with **more specific** declared parameter types wins. For `Log("ready")`, rule 2 removes the `params` overload, because `Log(string)` is applicable without expansion. Rule 4 removes `Log(string, int = 0)`, because it needs a default filled in and `Log(string)` does not. `Log(string)` is therefore better than both and is called. ## Tie-breakers only run on a tie These rules never override a better conversion. The runnable example shows four calls: | Call | Bound to | Reason | |---|---|---| | `Log("ready")` | `Log(string)` | tie-breakers: normal form, no default substituted | | `Log("ready", 2)` | `Log(string, int = 0)` | `2` to `int` is identity; to the `params` array it must box to `object` | | `Log("ready {0}", "disk")` | `Log(string, params object[])` | no other overload accepts a string second argument | | `Log("ready {0} {1}", 1, 2)` | `Log(string, params object[])` | only the expanded form takes three arguments | The second row is the one people misread: the `params` method is applicable, but converting `2` to `object` is a boxing conversion, and an identity conversion to `int` is better, so the comparison never reaches the tie-breakers. A related pair behaves the same way. With only `Q(string format, params object[] args)` and `Q(string format, int level = 0)`, the call `Q("x")` binds to the optional-parameter method: it is applicable in normal form, and the normal-form rule comes before the default-value rule. ## Two params overloads (C# 13) C# 13 added **params collections**, so a method may declare `params ReadOnlySpan<object?> args` instead of `params object?[] args`. When a facade offers both and a call uses the expanded form, as in `Log("ready {0}", 1)`, the compiler prefers the `ReadOnlySpan<T>` parameter, because C# 13's better-conversion rules rank a span ahead of an array of the same element type. Passing an existing `object[]` still binds to the array overload in its normal form, which is an identity match. How params collections themselves work belongs to the lesson on optional, named and params arguments. ## What to take into a code review - When overloads differ only by an optional parameter or a `params` tail, the short form wins every tie. Check that it does the same work, or a caller's `Log("ready")` will silently skip the level or formatting logic. - An overload with an optional parameter and one without are often redundant; removing one makes the binding obvious. - If a call must reach a specific overload, give it an argument only that overload accepts, instead of relying on a tie-breaker that a later overload can change. - Remember that every one of these choices is made when the caller is compiled. Adding a fourth `Log` overload to a published facade changes nothing for callers that are already built, and can change the binding of the same source line the next time they are rebuilt.

  • With only `Q(string format, params object[] args)` and `Q(string format, int level = 0)`, which does `Q("x")` call?
    `Q(string format, int level = 0)`. Both accept one string with the same identity conversion, so the tie-breakers run, and the rule that a method applicable in its normal form beats one applicable only in its expanded form comes before the rule about default values. The optional-parameter method is applicable in normal form; the `params` one needs expansion.
  • Why does `Log("ready", 2)` bind to `Log(string, int = 0)` and not to the `params object[]` overload?
    The conversions differ before any tie-breaker runs. For the `int` parameter, `2` is an identity match; for the expanded `params object[]` form, it must be boxed to `object`. An identity conversion is better than a boxing conversion, so `Log(string, int)` is the better function member.

  • A params overload is preferred because it can accept any number of arguments.
  • Overloads differing only by an optional parameter make Log("ready") ambiguous.
  • Tie-breakers can make a boxing conversion beat an identity conversion.
  • The overload with the most parameters always wins a tie.

Assumes C# 14 on .NET 10; the normal-form and default-value tie-breakers are older, and the rule that a params ReadOnlySpan<T> beats a params T[] arrived with C# 13 params collections.