Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple explicit interface implementation

I have the following base interface

public interface IBaseAction
{
   bool CanAct(...)
}

and two inheriting interface say

public interface IAction1 : IBaseAction{}

and

public interface IAction2 : IBaseAction{}

My problem is, I have a class which implements both, and I want to implement CanAct DIFFERENTLY.

public class ComplexAction : IAction1, IAction2
{
   bool IAction1.CanAct(...){} //doesn't compile as CanAct is not a member of IAction1!!
}

ComplexAction c=new ComplexAction();
var a1 = (IAction1)c;
var a2 = (IAction2)c;
a1.CanSave(); //THESE TWO CALLS SHOULD BE IMPLEMENTED DIFFERENTLY
a2.CanSave();

Is there a reasonably clean way to do this?
(Also, my interfaces have semantic meaning and at least three more functions, so it is out of the question to throw out the whole hierarchy, but I'd be willing to copy bool CanAct to every inheriting interface if that is the only solution (there are 4-6 of them))

like image 366
TDaver Avatar asked Jun 19 '11 21:06

TDaver


People also ask

Can same interface be used in multiple?

A class can implement multiple interfaces and many classes can implement the same interface. A class can implement multiple interfaces and many classes can implement the same interface.

Can interface implement another interface?

An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.

Can a class implement two interfaces in case they have the same member names C#?

C# allows the implementation of multiple interfaces with the same method name.

Can interface inherit another interface C#?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.


2 Answers

And what the CLR is supposed to do if someone calls ((IBaseAction)a1).CanSave()? There could be just one implementation for IBaseAction.CanSave(). So I think you can't do this conceptually.

This is a fundamental problem of multiple inheritance called the diamond problem. The bottom line is: if you hit it, your type hierarchy design is definitely wrong. E.g. in this particular case, you're better off with the Role class model (also known as the Role pattern).

like image 185
Ivan Danilov Avatar answered Sep 24 '22 22:09

Ivan Danilov


You can't do what you describe. Just imagine what would happen if a client requests the IBaseAction interface. Which one should be returned?

It sounds to me like each action should be implemented by separate objects.

like image 43
David Heffernan Avatar answered Sep 22 '22 22:09

David Heffernan