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#.
In C# you don’t have multiple inheritance. You can circumvent this limitation by using composition.
Define your interface like this (
Functionneeds not to be defined here):Declare an abstract class with an abstract
Functionand implementing this interface:From this abstract class you can derive a concrete implementation. This is not yet your “final” class, but it will be used to compose it.
Now let’s come to your “final”, composed class. It will derive from
SomeBaseClassand implementIMyInterfaceby integrating the functionality ofConcreteMyInterface:UPDATE
In C# you can declare local classes. This comes even closer to multiple inheritance, as you can derive everything within your composing class.