In C# 8.0 interfaces can have default implementations for some members. These implementations are explicit meaning that they are inaccessible through the class instance and we must cast to the interface type to call them. Is there a way to expose this implementation on the class instance with the same name? It is possible to expose it under another name by casting the this pointer to the interface type and calling the method like:
void A()
{
((ISomething)this).B();
}
However I can't seem to find a way to expose the implementation with the original name of B because if I declare a method B it counts as the one implementing the interface which causes infinite recursion. Is there some way to expose the implementation without copying it or there is something I am missing?
To clarify, I am looking for a way to achieve traits-like functionality i.e. being able to import the implementation from the interface directly into the class's public API without changing the method name (presumably the name in the interface was the best one). The question is not about how to call the method as a user of the class but how to make it part of the public API of the class.
Extension methods are one solution but default interface implementations have access to protected members and can be overloaded.
There's no simple way to do it; various ugly workarounds are possible that all boil down to delegating to some other method (a static method or relying on a helper class that doesn't itself implemented the method) to access it, and even then you need to pass in state somehow. There's a proposal for a
base(T)
syntax, draft specification here, which should allowbase(ISomething).B()
to refer to the implementation without causing a cyclic reference. This was originally slated to be part of C# 8, but this proved to be too ambitious and it was cut. As of writing, it's a candidate for inclusion in C# 9.