skip to content

In C#, when a type has an instance method and an imported extension method shares its name, which one does a call bind to, and why?

level: middleimportance: must knowfreq 58%

answer

  1. two-phase lookup
  2. applicable, not best
  3. static type of the receiver
  4. decided when the caller compiles

basics

~20 s

An applicable instance method always wins, even when the extension's parameters match better: the compiler searches extensions only when instance lookup finds nothing applicable. The choice is fixed when the caller compiles, so an extension never overrides.

solid answer

~40 s

Binding happens in two phases. First the compiler looks for an applicable member on the receiver's **static** type; if it finds one, it uses it and never looks at extensions. Only when no instance member is applicable does it collect the imported extension methods and run overload resolution on them. So `report.Print(42)` calls an instance `Print(object)` even though an extension `Print(this IReport, int)` would be an exact match. The same call through a variable typed `IReport`, which declares no `Print`, reaches the extension. And because the decision is made at compile time, adding an instance method to a library later silently changes what callers bind to the next time they are recompiled.

code

csharp · 22 lines
csharp
using Shared.Reporting;

var report = new Report();
report.Print(42);          // instance Print(object) is applicable, so it wins
IReport viaInterface = report;
viaInterface.Print(42);    // IReport declares no Print, so the extension binds
ReportExtensions.Print(report, 42);

public interface IReport { }
public class Report : IReport
{
    public void Print(object value) => Console.WriteLine($"instance Print(object): {value}");
}

namespace Shared.Reporting
{
    public static class ReportExtensions
    {
        public static void Print(this IReport report, int value) =>
            Console.WriteLine($"extension Print(int): {value}");
    }
}

go deeper

for a junior

Remember the headline: if the type already has an applicable method with that name, the extension is never called.

for a middle

Explain the two phases, applicability before betterness, and why the interface-typed variable reaches the extension while the class-typed one does not.

for a senior

Diagnose behaviour that changes after a dependency upgrade and rebuild, and spot extensions that are dead code because the type gained a member.

for a principal

Weigh naming and namespace policy for shared extension libraries so that framework or vendor additions cannot silently take over calls.

## Two-phase lookup When the C# compiler binds a call such as `report.Print(42)`, extension methods are a **fallback**, not peers of the type's own members. The order is: 1. **Member lookup on the receiver's static type.** The compiler collects the methods named `Print` declared on, or inherited by, the compile-time type of `report`, and keeps the **applicable** ones: those the arguments can convert to. 2. **If any instance method is applicable, binding is finished.** Overload resolution picks the best among those instance candidates, and extension methods are never considered. 3. **Only if none is applicable** does the compiler gather the extension methods named `Print` from the static classes in scope and run overload resolution again, with the receiver as the first argument. The documentation states the consequence plainly: an extension member with the same name and signature as a member of the type is never called. ## Applicable beats better The rule is about **applicability**, not about which method would be the better match. In the example, `Report` declares `Print(object value)` and an imported extension declares `Print(this IReport report, int value)`. For `report.Print(42)` the extension is an exact match for `int`, while the instance method needs a boxing conversion to `object`, yet the instance method wins because it is applicable and phase 2 ends the search. The program prints `instance Print(object): 42`. The compiler gives **no warning** when an extension method is shadowed this way, so the mistake usually surfaces as a puzzled "why is my extension never hit?" in a debugger. ## The static type of the receiver decides Phase 1 looks at the **compile-time type of the expression**, not at the object it refers to at run time: | Call | Static type of the receiver | Binds to | |---|---|---| | `report.Print(42)` | `Report` | instance `Print(object)` | | `viaInterface.Print(42)` | `IReport` (declares no `Print`) | extension `Print(this IReport, int)` | | `ReportExtensions.Print(report, 42)` | not a member call | extension, called as a static method | The same object can therefore reach different methods depending on how the variable is typed. That is not polymorphism: nothing is dispatched at run time, the compiler simply saw different member lists. ## Decided when the caller compiles Because an extension call compiles to a direct static call, the binding is baked into the **caller's** IL: - If a library later adds an instance `Print(int)` to `Report`, an application compiled against the old version keeps calling the extension until it is rebuilt. - When the application is rebuilt, the call **silently switches** to the new instance method, without any diagnostic. - An extension therefore cannot be used to "patch" or override a type's behaviour. To change behaviour you need a virtual member and a subclass, a wrapper type, or a change to the type itself. C# 14 extension properties follow the same rule: `ImmutableArray<T>` has its own `IsEmpty` property, so for an `ImmutableArray<T>` value an extension `IsEmpty` declared for `IEnumerable<T>` is reached only through an expression typed as `IEnumerable<T>`, or by calling its accessor in static form. ## Interfaces and generic receivers Extensions are most often written for **interfaces** and **type parameters**, and the same rule applies there: - An extension on `IReport` serves every implementer, but any implementer that declares an applicable `Print` of its own shadows it for callers typed as that class. - An extension written as `Print<T>(this T item, int value)` is a candidate for every receiver type, yet still loses to any applicable instance `Print`. - Adding a member to an interface you publish has the same effect for callers typed as the interface: after they recompile, the interface member wins. The shadowing is per call site, decided by the static type the compiler sees, which is why the same helper can work in one file and be ignored in another. ## Forcing the extension when you need it - Call it in the **static form**: `ReportExtensions.Print(report, 42)`. - Call it through a variable or cast whose static type does not declare the member, such as the interface. - Rename the extension; a name the type does not use cannot be shadowed. Attributes do not help here. `[OverloadResolutionPriority]` (C# 13) only ranks candidates within one declaring type, and extension candidates are never collected once an instance member applies. ## What this means in code review - An extension whose name matches a type's member, with compatible parameters, is dead code for every caller typed as that type. - Prefer extension names that the extended type is unlikely to add, especially on types you do not own. - When a dependency upgrade changes behaviour after a rebuild with no code change, check whether a new instance member now shadows an extension.

  • A library's next version adds an instance Print(int) to Report. What happens to an application that called the Print extension?
    Its compiled IL still contains a static call to the extension, so it keeps calling the extension until it is rebuilt. After the rebuild, `report.Print(42)` binds to the new instance method with no warning. The behaviour change arrives with a recompile, not with the library upgrade itself.
  • Does the instance-wins rule also apply to C# 14 extension properties?
    Yes. Extension properties are resolved like extension methods, after member lookup on the type. `ImmutableArray<T>` has its own `IsEmpty`, so on an `ImmutableArray<T>` value an extension `IsEmpty` declared for `IEnumerable<T>` is reached only through an expression whose static type is `IEnumerable<T>`.
  • Why does the same object reach different methods through a Report variable and an IReport variable?
    Because lookup uses the compile-time type of the receiver expression. `Report` declares an applicable `Print`, so that call binds to it; `IReport` declares none, so the compiler falls back to extensions. Nothing is dispatched at run time; the compiler saw two different member lists.

  • The extension wins because its parameter types match the arguments more exactly.
  • A call with both candidates available is reported as ambiguous, CS0121.
  • An extension method can override an existing instance method.
  • Which method runs depends on the object's run-time type, like a virtual call.
  • The compiler warns when an instance member shadows an extension method.