How to call/use the interface default implementation? #97768
-
Let's assume that I have the following: internal interface IService
{
void DoSomething(string text);
void DoSomethingDefault(string text) => Console.WriteLine($"Default: {text}");
}
internal sealed class MyService : IService
{
public void DoSomething(string text)
{
Console.WriteLine(text);
// Calling the method as is
// DoSomethingDefault(text);
// Casting to the interface
(this as IService).DoSomethingDefault(text);
}
// Or using the default implementation
// public void DoSomethingDefault(string text) => ???
} Also, let's assume that I like the default implementation of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Casts are required to call default interface methods (DIMs), as per the specification. To call DIMs, one must be interacting with an interface object, not directly with a class/struct. Also, casts are free when you're going "up" the inheritance tree (and not boxing); They only "cost" something if you're going "down" the tree (such as from an https://andrewlock.net/understanding-default-interface-methods/ If you're asking to "forward" the default implementation to remove the constrained call requirement, you can do so by overriding the interface method in the derived type, but just have it forward to the default: public class MyService : IService
{
public void DoSomething(string text)
{ ... }
public void DoSomethingDefault(string text) =>
(this as IService).DoSomethingDefault(text);
} |
Beta Was this translation helpful? Give feedback.
Casts are required to call default interface methods (DIMs), as per the specification. To call DIMs, one must be interacting with an interface object, not directly with a class/struct.
Also, casts are free when you're going "up" the inheritance tree (and not boxing); They only "cost" something if you're going "down" the tree (such as from an
IService
toMyService
) as type checking must be performed. In addition, "constrained calls" like you're doing will not box if the original object is a value-type (struct); The JIT will optimize out the boxing in such situations.https://andrewlock.net/understanding-default-interface-methods/
If you're asking to "forward" the default implementation to …