See the documentation at https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/default-interface-members-versions
That cast from
SampleCustomer
toICustomer
is necessary. TheSampleCustomer
class doesn’t need to provide an implementation forComputeLoyaltyDiscount
; that’s provided by theICustomer
interface. However, theSampleCustomer
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");
}
}