Declaring member function in interface
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.
You can define MyAction
as extension method:
public interface IMyInterface
{
void Function();
}
public static class MyInterfaceExtensions
{
public static void MyAction(this IMyInterface obj)
{
obj.Function();
}
}
Example:
public class HelloWorld : IMyInterface
{
public void Function()
{
Console.WriteLine("Hello World");
}
public static void Main(string[] args)
{
new HelloWorld().MyAction();
}
}
Output:
Hello World
In C# you don't have multiple inheritance. You can circumvent this limitation by using composition.
Define your interface like this (Function
needs not to be defined here):
public interface IMyInterface
{
void MyAction();
}
Declare an abstract class with an abstract Function
and implementing this interface:
public abstract class MyInterfaceBase : IMyInterface
{
public void MyAction()
{
// Do stuff depending on the output of Function().
Function();
}
protected abstract void Function();
}
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.
public class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
Now let's come to your "final", composed class. It will derive from SomeBaseClass
and implement IMyInterface
by integrating the functionality of ConcreteMyInterface
:
public class SomeBaseClass
{
}
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
}
UPDATE
In C# you can declare local classes. This comes even closer to multiple inheritance, as you can derive everything within your composing class.
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
private class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
}