Domanda

I have an Interface:

public interface IMessager
{
    void ShowMessage();
}

Is there any way to implement this interface using extension methods?

public static class Extensions
{
  public static void ShowMessage(this MyClass e)
  {
      Console.WriteLine("Extension");
  }
}

and a class that implement it:

public class MyClass:IMessager
{
    public void ShowMessage()
    {
        ShowMessage(); // I expect that program write "Extension" in console
    }
}

But when I run the program I get the System.StackOverflowException.

È stato utile?

Soluzione

The code you posted is just a method calling itself recursively (hence the StackOverflowException).

I'm not entirely sure what you're trying to accomplish but to answer your question

Is there any way to implement this interface using extension methods?

No.

To be a bit more pragmatic about this though, if your aim is to only write your method once you have a few options:

1. Call the extension explicitly

public class MyClass:IMessager
{
    public void ShowMessage()
    {
        Extensions.ShowMessage(this);
    }
}

although as pointed out in comments, this basically defeats the point of using the extension method. Additionally there is still "boiler-plate code" such that every time you implement your interface you have to call the static method from within the method (not very DRY)

2. Use an abstract class instead of an interface

public abstract class MessengerBase
{
    public void ShowMethod() { /* implement */ }
}

public class MyClass : MessengerBase {}

...

new MyClass().ShowMethod();

This issue with this though is that you can't inherit from multiple classes.

3. Use extension on the interface

public interface IMessenger { /* nothing special here */ }

public class MyClass : IMessenger { /* also nothing special */ }

public static class MessengerExtensions
{
    public static void ShowMessage(this IMessenger messenger)
    {
        // implement
    }
}

...

new MyClass().ShowMessage();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top