Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying multiple interfaces for a parameter

Tags:

I have an object that implements two interfaces... The interfaces are:

public interface IObject {     string Name { get; }     string Class { get; }     IEnumerable<IObjectProperty> Properties { get; } } public interface ITreeNode<T> {     T Parent { get; }     IEnumerable<T> Children { get; } } 

such that

public class ObjectNode : IObject, ITreeNode<IObject> {     public string Class { get; private set; }     public string Name { get; private set; }     public IEnumerable<IObjectProperty> Properties { get; set; }     public IEnumerable<IObject> Children { get; private set; }     public IObject Parent { get; private set; } } 

Now i have a function which needs one of its parameters to implement both of these interfaces. How would i go about specifying that in C#?

An example would be

public TypedObject(ITreeNode<IObject> baseObject, IEnumerable<IType> types, ITreeNode<IObject>, IObject parent) {     //Construct here } 

Or is the problem that my design is wrong and i should be implementing both those interfaces on one interface somehow

like image 437
TerrorAustralis Avatar asked Nov 01 '10 21:11

TerrorAustralis


People also ask

Can there be multiple interfaces?

Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior.

Can you implement 2 interfaces?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

How do you implement multiple interfaces in C++?

You can implement each individial interface using a separate template and then chain the templates to construct the derived object as if from building blocks. This method was also used by venerable ATL library to implement COM interfaces (for those of us old enough).

What if multiple interfaces have same method?

No, its an error If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.


2 Answers

public void Foo<T>(T myParam)     where T : IObject, ITreeNode<IObject> {     // whatever } 
like image 124
Jesse McGrew Avatar answered Nov 02 '22 23:11

Jesse McGrew


In C#, interfaces can themselves inherit from one or more other interfaces. So one solution would be to define an interface, say IObjectTreeNode<T> that derives from both IObject and ITreeNode<T>.

like image 33
Anders Fjeldstad Avatar answered Nov 03 '22 00:11

Anders Fjeldstad