Search code examples
c#c#-8.0default-interface-member

Calling C# interface default method from implementing class


C# 8 supports default method implementations in interfaces. My idea was to inject a logging method into classes like this:

public interface ILoggable {
    void Log(string message) => DoSomethingWith(message);
}

public class MyClass : ILoggable {
    void MyMethod() {
        Log("Using injected logging"); // COMPILER ERROR
    }
}

I get a compiler error: "The name does not exist in the current context"

Is it impossible to use default method implementations in this way?

EDIT:

For the correct response regarding C# rules, see the accepted answer. For a more concise solution (the original idea of my question!) see my own answer below.


Solution

  • See the documentation at "Upgrade with default interface methods":

    That cast from SampleCustomer to ICustomer is necessary. The SampleCustomer class doesn't need to provide an implementation for ComputeLoyaltyDiscount; that's provided by the ICustomer interface. However, the SampleCustomer class doesn't inherit members from its interfaces. That rule hasn't changed. In order to call any method declared and implemented in the interface, the variable must be the type of the interface, ICustomer in this example.

    So the method needs to be something like:

    public class MyClass : ILoggable {
        void MyMethod() {
            ILoggable loggable = this;
            loggable.Log("Using injected logging");
        }
    }
    

    or:

    public class MyClass : ILoggable {
        void MyMethod() {
            ((ILoggable)this).Log("Using injected logging");
        }
    }