Calling C# interface default method from implementing class

See the documentation at https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/default-interface-members-versions

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 is something like

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

Leave a Comment