skip to content

In C#, IPaymentGateway gains a Refund method with a default body; why does adapter.Refund(...) on a LegacyCardAdapter variable fail to compile, and what runs through the interface?

level: seniorimportance: should knowfreq 40%

answer

  1. interface members are not inherited
  2. most specific implementation
  3. class beats interface
  4. CS8705 in a diamond
  5. needs runtime support

basics

~20 s

A class does not inherit an interface's default method, so the class-typed call is CS1061. Through IPaymentGateway the runtime runs the most specific implementation: the class's own Refund, else a derived interface's override, else the default body.

solid answer

~50 s

A default interface method (C# 8) is a virtual member of the interface, not a member the implementing class gains. `adapter.Refund(...)` on a `LegacyCardAdapter` variable is CS1061, and calling `Refund(...)` by name inside the class is CS0103; you call it through `IPaymentGateway`. That call dispatches to the **most specific implementation**: a public `Refund` the class already declares (or an explicit `IPaymentGateway.Refund`) beats any interface body, and an override in a derived interface beats the base interface's body. If two unrelated derived interfaces both override it and a class implements both without its own version, the class fails with CS8705; there is no `base(ICardGateway).Refund()` call to delegate with, because that syntax was designed for C# 8 and is still not implemented in C# 14. The feature needs runtime support, so compiling for a runtime without it is CS8701.

code

csharp · 30 lines
csharp
#:property PublishAot=false
IPaymentGateway legacy = new LegacyCardAdapter();
legacy.Refund("tx-1", 5m);                  // no class implementation: the default body runs
IPaymentGateway modern = new ModernCardAdapter();
modern.Refund("tx-2", 5m);                  // the class's public method is more specific

var adapter = new LegacyCardAdapter();
// adapter.Refund("tx-3", 5m);              // error CS1061: the class does not inherit Refund
((IPaymentGateway)adapter).Refund("tx-3", 5m);
Console.WriteLine(typeof(LegacyCardAdapter).GetMethod("Refund") is null);   // True

public interface IPaymentGateway
{
    void Charge(decimal amount);

    void Refund(string transactionId, decimal amount)          // added in v2 with a body
        => Console.WriteLine($"default Refund: {GetType().Name} cannot refund {transactionId}");
}

public class LegacyCardAdapter : IPaymentGateway
{
    public void Charge(decimal amount) { }
    // public void Undo() => Refund("tx", 1m);  // error CS0103: the name 'Refund' does not exist
}

public class ModernCardAdapter : IPaymentGateway
{
    public void Charge(decimal amount) { }
    public void Refund(string transactionId, decimal amount) => Console.WriteLine($"refund {transactionId}");
}

go deeper

for a junior

Remember that a default interface method is called through the interface type, never through the class variable.

for a middle

Explain the most specific implementation rule: a class implementation first, then a derived interface's override, then the interface's own body.

for a senior

Diagnose CS1061, CS0103 and CS8705 around default methods, resolve a diamond with a class implementation plus a static helper, and know why base(Interface) calls do not work.

for a principal

Treat default methods as a versioning tool with costs: invisible on concrete types, a runtime requirement for every consumer, and diamonds once interfaces branch.

## What a default interface method is Since C# 8 an interface member may have a body: ```csharp public interface IPaymentGateway { void Charge(decimal amount); void Refund(string transactionId, decimal amount) => Console.WriteLine($"default Refund: {GetType().Name} cannot refund {transactionId}"); } ``` The body is the **default implementation**. Existing implementers such as `LegacyCardAdapter`, which only implements `Charge`, keep compiling and keep loading, and calls through `IPaymentGateway` reach the body. The member is still an interface member that is `virtual` by default; it is not copied into the class. ## Why the class-typed call fails C# has always said that a class does not inherit members from its interfaces, and C# 8 kept that rule: - `adapter.Refund("tx-3", 5m)` with `adapter` typed as `LegacyCardAdapter` is CS1061, "does not contain a definition for 'Refund'". - A method inside `LegacyCardAdapter` calling `Refund(...)` by simple name is CS0103, "The name 'Refund' does not exist in the current context". - Reflection agrees: `typeof(LegacyCardAdapter).GetMethod("Refund")` returns `null`. The call has to go through the interface: `((IPaymentGateway)adapter).Refund(...)`, or a variable typed `IPaymentGateway`. Code that holds concrete types, including extension methods and helpers written against the class, never sees the default method. ## Which body runs: the most specific implementation For each interface member, a class must have exactly one **most specific implementation**, and the runtime calls that one. The rules from the C# 8 design are: 1. An implementation declared in a **class** beats any implementation declared in an interface. A `ModernCardAdapter` that already had `public void Refund(string, decimal)` keeps running its own method after the interface gains a default body. 2. Between interfaces, an override in a **derived interface** beats the one in the interface it derives from. A derived interface overrides with explicit syntax: `void IPaymentGateway.Refund(string id, decimal amount) => ...`. 3. If no override exists, the interface's own default body is the implementation. ## The diamond When `ICardGateway` and `IWalletGateway` both derive from `IPaymentGateway` and both override `Close`, neither is more specific than the other. A class implementing both, with no `Close` of its own, fails with CS8705: "Interface member 'IPaymentGateway.Close()' does not have a most specific implementation. Neither 'ICardGateway.IPaymentGateway.Close()', nor 'IWalletGateway.IPaymentGateway.Close()' are most specific." The fix is a class-level implementation, which is more specific than either interface. Two limits apply to that fix: - `base(ICardGateway).Close()` was designed for C# 8 to call one interface's body non-virtually, but it was not implemented then, and the C# 14 compiler still rejects it (CS0175). - `((ICardGateway)this).Close()` from inside the class dispatches back to the class's own `Close`, so it recurses instead of reaching the interface body. Shared logic therefore goes into a `static` (often `protected static`) helper on the interface that both the interface body and the class can call. ## Runtime support and value types - Default implementations need runtime support, which the CLR gained in .NET Core 3.0. The compiler checks whether the target runtime supports it; compiling for one without the feature (.NET Framework, for example) is CS8701, "Target runtime doesn't support default interface implementation." At run time, `RuntimeFeature.IsSupported(RuntimeFeature.DefaultImplementationsOfInterfaces)` reports the support. - A struct that relies on a default body runs it on a boxed copy, whether the call goes through an interface-typed variable or through a generic method constrained to the interface; a default body that changes a property changes the copy, not the original variable. ## Compile time and run time Whether the call compiles is decided by the static type of the receiver when the caller is compiled. Which body runs is decided at run time from the object's type, so an updated library that adds a more specific override in a derived interface changes the result for already-compiled callers. ## Diagnosing a default method in review When a default method "does nothing", "cannot be found" or "runs the wrong body", work through the same steps: 1. **What is the receiver's static type?** A class-typed receiver never sees the default method; CS1061 or CS0103 means the call must go through the interface. 2. **Does the class already declare a matching public member?** If so, that member is the implementation, and the default body never runs for this class, even if the member was written for another purpose years earlier. 3. **Do derived interfaces override it?** Look for explicit `void IPaymentGateway.Refund(...)` declarations in interfaces the class implements; the most derived one wins. 4. **Is the class in a diamond?** If two branches override the member, the class needs its own implementation, and that implementation must not cast `this` back to one of the branches. 5. **Was the caller or the implementer recompiled?** Dispatch is resolved at run time, so a new package version can change which body runs without any rebuild.

  • How do you resolve CS8705 when two derived interfaces both override the same default method?
    Give the class its own implementation, public or explicit, because a class implementation is more specific than any interface's. You cannot delegate with `base(ICardGateway).Close()`, which the C# 14 compiler still rejects, and casting `this` to `ICardGateway` calls the class's own method again. Move the shared logic into a static helper on the interface and call it from both places.
  • What happens when a struct relies on a default interface method that changes a property?
    The default body always runs on a boxed copy, whether the struct is converted to the interface or passed to a generic method constrained to it. The body updates that copy, so the original variable keeps its old value: a counter incremented through `((IRetryPolicy)counter).RecordFailure()` still reads 0 on `counter`.
  • Can a library that targets .NET Framework declare default interface methods?
    No. The CLR gained default implementations in .NET Core 3.0, and the compiler refuses a body in an interface when the target runtime lacks the feature, reporting CS8701, "Target runtime doesn't support default interface implementation." A shared package that still targets .NET Framework must evolve its interfaces another way.

  • A class implementing the interface inherits the default method as a public member.
  • Calling Refund() by name inside the class reaches the default body.
  • The interface's default body overrides a Refund the class already declares.
  • Two interfaces overriding the same default method are resolved by base-list order.
  • base(ICardGateway).Close() delegates to one interface's body in a diamond.
  • Default interface methods are compiler sugar that runs on any .NET runtime.