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.
See the documentation at "Upgrade with default interface methods":
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 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");
}
}