Declaring member function in interface

vanna picture vanna · Jan 24, 2013 · Viewed 30.3k times · Source

Firstly I am pretty new to C#. I would like to have an interface declare a member function like in the following piece of code

interface IMyInterface {
    void MyAction() {
        // do stuff depending on the output of function()
    }
    void Function();
}

here Function is pure virtual and should be implemented by children of IMyInterface. I could use an abstract class instead of an interface but then I could not inherit from other classes... Say for example that MyAction is recursiverly searching a directory for files and applying Function to any file found to make my example clear.

How to change my design in order to overcome the constraint that interfaces cannot implement classes ?

Edit : In C++ what I would do is using templates as such

template<class A>
static void MyAction(const A& a) {
    // do stuff depending on the output of A::Function()
};

class MyClass {
    void Function();
};

I was wondering if there were an elegant way to do this using interfaces in C#.

Answer

Reed Copsey picture Reed Copsey · Jan 24, 2013

The only way to directly handle this would be to use an abstract class, as the interface cannot contain "logic" of any form, and is merely a contract.

One alternative, however, would be to make an interface and a static class. You could then place your logic in an extension method using the interface.

public interface IMyInterface {
    void Function();
}

public static class MyInterfaceExtensions {
    public static void MyAction(this IMyInterface object)
    {
       // use object.Function() as needed
    }
}

The main disadvantages here are more types, which reduces maintainability, and a lack of discoverability.