Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# 8.0 is there a way to expose default member implementation on the class?

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.

like image 506
Stilgar Avatar asked Oct 23 '25 21:10

Stilgar


1 Answers

One possibility is to provide properties for them. This is what I do when I need to refer to explicit implementations from within the class.

class Something : IInterfaceA, IInterfaceB {
   public IInterfaceA A => this;
   public IInterfaceB B => this;
}

...

something.A.AMethod();
something.B.BMethod();

You might also consider using extension methods instead of default implementations. They are somewhat similar anyway.

interface IInterface {
}

static class IInterfaceExtensions {
   public static void DoSomething(
      this IInterface me
   ) {
      // do something
   }
}
like image 152
Dave Cousineau Avatar answered Oct 26 '25 11:10

Dave Cousineau