32

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Andi
  • 3,234
  • 4
  • 32
  • 37
  • Take a look at this: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation – user743414 Sep 02 '19 at 19:46

8 Answers8

26

See the documentation at https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/default-interface-members-versions

That cast from SampleCustomer to ICustomer is necessary. The SampleCustomer class doesn't need to provide an implementation for ComputeLoyaltyDiscount; that's provided by the ICustomer interface. However, the SampleCustomer 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");
    }
}
BurnsBA
  • 4,347
  • 27
  • 39
  • 5
    any idea _why_ is this ? that is why class doesn't inherit members from its interfaces ? – kofifus Jan 06 '20 at 05:49
  • 2
    @kofifus Imagine if the class implements more than one interface and two interfaces have default implementations of a method with the same name. Which one would get called? This is [the problem with multiple inheritance](https://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance) that c# is trying to avoid. – John Wu Jul 13 '21 at 16:09
  • 2
    As long as there is only one implementation, the compiler could be satisfied with that. It should be known at the time of compiling? Error is fine as soon as there are multiple implementations. – Andi Mar 05 '22 at 16:53
  • 1
    You can load/create additional interfaces at runtime. – BurnsBA Nov 13 '22 at 20:13
12

If you want to avoid clutter and repetitive casting you can add a single property which casts the type as the interface:

public class MyClass : ILoggable 
{
    ILoggable AsILoggable => (ILoggable)this;

    void MyMethod() 
    {
        AsILoggable.Log("Using injected logging"); 
    }
}

But this is off. It seems wrong, regardless of how it's done. From the documentation:

The most common scenario is to safely add members to an interface already released and used by innumerable clients.

When there was some concern about having implementations in interfaces - which previously had none - this was the sentence that made sense of it. It's a way to add to an interface without breaking classes that already implement it.

But this question implies that we are modifying the class to reflect a change to an interface it implements. It's the exact opposite of the stated use case for this language feature.

If we're already modifying the class, why not just implement the method?

public void Log(string message) => DoSomethingWith(message);

When we add a default interface implementation, we provide an implementation to consumers of the interface - classes that depend on an abstraction.

If we depend on the default interface implementation from within the class that implements the interface, then a change to the interface becomes, in effect, a change to the internal implementation of the class. That's not what an interface is for. An interface represents external-facing behavior, not internal implementation.

It's as if the class is stepping outside of itself, looking back in at itself as an external consumer, and using that as part of its internal implementation. The class doesn't implement the interface, but it depends on it. That's weird.

I won't go so far as to say that it's wrong, but it feels like an abuse of the feature.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • 2
    It's not an abuse, it's a core use case - traits. The OP's code comes from [this blog post](https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/) by Mads Torgersen. That logging code is *not* an internal implementation, it's a trait provided to the class. The code is actually *external* to the class and can't communicate with it except through interface methods - that's why abstract methods are there – Panagiotis Kanavos Sep 03 '19 at 10:03
  • 1
    In the past people attempted to add eg logging or undoing to a class with code like `MyClass : Loggable` or `MyClass:Undoable`, composition/delegation, or through the use of reflection. Needless to say, the first attempt abuses inheritance, delegation, adds a lot of complexity and reflection is too slow. – Panagiotis Kanavos Sep 03 '19 at 10:08
  • 3
    [Microsoft](https://learn.microsoft.com/de-de/dotnet/csharp/whats-new/csharp-8) states: "Default interface members also enable scenarios similar to a "traits" language feature." - I don't think it feels like abuse! Just implementing the `Log` method in the class is no option for me. Other than in this simple example, the `ILogging` interface contains lots of methods which I want to use within many classes. – Andi Sep 03 '19 at 12:53
  • 1
    @PanagiotisKanavos - That's why I qualify everything and try to avoid absolute statements. I'm going to struggle with this one. Just so I can get my head around this - are you saying that a core use case was for a class to internally cast *itself* as an interface it implements so that it can call a method it doesn't implement of an interface it partially implements? I'm having a hard time with that, but I can get over it. – Scott Hannen Sep 03 '19 at 13:16
  • Not sure if you were implying this, but I have to state that default interface methods are a mess. Microsoft shipped them too soon and they are a half-baked idea that are barely useful in current form. – MgSam Feb 08 '23 at 21:36
  • I haven't had a use for them, although I once answered a question where they were what someone needed. My particular concern was for this weird use case where a class implements an interface and then casts itself as that interface so it can call the static method. That's some weird stuff. – Scott Hannen Feb 09 '23 at 13:35
8

In CLR all interface member implementations are explicit, so in your code Log will be available in instances of ILoggable only, like it's recommended to do here:

((ILoggable)this).Log("Using injected logging")
ingvar
  • 4,169
  • 4
  • 16
  • 29
5

The problem with the answers that cast the class to an interface is that it may or may not call the default interface method, depending on whether or not the class has implemented a method to override the default method.

So this code:

((ILoggable)this).Log(...)

ends up calling the default interface method, but only if there is no interface method defined in the class that overrides the default method.

If there is a method in the class that overrides the default method, then that is the method that will be called. This is usually the desired behavior. But, if you always want to call the default method, regardless of whether or not the implementing class has implemented its own version of that interface method, then you have a couple of options. One way is to:

  1. Declare the default method as static. Don't worry, you will still be able to override it in a class that inherits from it.
  2. Call the default method using the same type of syntax when calling a static method of a class, only substitute the interface name for the class name.

See this answer for a code example, along with an alternative way of calling a default interface method.

Bob Bryan
  • 3,687
  • 1
  • 32
  • 45
  • yes it was strange isn't it? implementing class has an interface method implemented, and you are never again able to call the default interface method :| – Dominik Miedziński Aug 12 '23 at 18:42
4

Here is an alternative solution to the ones already suggested:

Extension methods:

public static class LogExtensions
{
  public static void Log<T>(this T logger, string message) where T : ILoggable => logger.Log(message);
}

public class MyClass : ILoggable {
    void MyMethod() {
        this.Log("Using injected logging");
    }
}

This might be useful when ILoggable contains many methods / is implemented in many classes.

  • this still allows for Log to be overwritten in MyClass and the override to be called
  • essentially just syntactic sugar, shortening ((ILoggable)this) to this

Incorrect alternative (see comment)

simply implement the interface method

public class MyClass : ILoggable {
    void MyMethod() {
        Log("Using injected logging");
    }

    public void Log(string message) => ((ILog)this).Log(message);
}

This allows the method to be called directly, without having to write the cast to ILog each time.

Things to note:

  • this will make the method available on MyClass to outside users of it as well, where previously it was only available when an instance of MyClass is cast to / used as ILog
  • if you want to use 10 different methods from ILog in your class, you probably don't want to implement them all.
  • on the flipside, there are many scenarios where this is the "natural" / intended approach, primarily when MyClass extends the interface method with some custom logic (like ((ILog)this).Log("(MyClass): " + message) )
enzi
  • 4,057
  • 3
  • 35
  • 53
  • 1
    Unfortunately, the first solution causes a stack overflow when `Log` is called, because it will call itself. If you implement an interface method explicitly in the class, it is then called instead of the default implementation (and casting the instance to `ILog` doesn't change that). – Robert Husák Dec 23 '22 at 12:02
  • 1
    Robert is correct, I updated the answer. – enzi Mar 20 '23 at 15:00
3

From reading an article about these default methods, I think you should try to upcast it to the interface:

((ILoggable)this).Log("Using injected logging")

I haven't checked it, just my thought according to this article.

Pang
  • 9,564
  • 146
  • 81
  • 122
Vladimir
  • 3,774
  • 3
  • 23
  • 27
2

The accepted answer and the other responses are correct. However, what I wanted is a concise call of the Log method. I achieved that with an extension method on the ILoggable interface:

public static class ILoggableUtils { // For extension methods on ILoggable
    public static void Log(this ILoggable instance, string message) {
         DoSomethingWith(message, instance.SomePropertyOfILoggable);
    }
}

In this way, I can at least call this.Log(...); in my class instead of the ugly ((ILoggable)this).Log(...).

Andi
  • 3,234
  • 4
  • 32
  • 37
1

My solution is adding new abstract class between interface and it's implementations:

public interface ILoggable {
    void Log(string message);
    void SomeOtherInterfaceMethod();
}

public abstract class Loggable : ILoggable  {
    void Log(string message) => DoSomethingWith(message);
    public abstract void SomeOtherInterfaceMethod(); // Still not implemented
}

public class MyClass : Loggable {
    void MyMethod() {
        Log("Using injected logging"); // No ERROR
    }

    public override void SomeOtherInterfaceMethod(){ // override modifier needed
        // implementation
    };
}
Akmal Salikhov
  • 818
  • 3
  • 12
  • 25