TerrorAustralis
TerrorAustralis

Reputation: 2923

Specifying multiple interfaces for a parameter

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

Upvotes: 35

Views: 14970

Answers (4)

C. Dragon 76
C. Dragon 76

Reputation: 10062

It's probably easiest to define an interface that implements both IObject and ITreeNode.

public interface IObjectNode<T> : IObject, ITreeNode<T>
{
}

Another option, in case you don't expect the above interface would be used often, is to make the method/function in question generic.

public void Foo<T>(T objectNode) where T : IObject, ITreeNode<IObject>

Upvotes: 3

anivas
anivas

Reputation: 6547

public  void MethodName<TParam1, TParam2>(TParam1 param1, TParam2 param2) 
    where TParam1 : IObject
    where TParam2 : ITreeNode<IObject> 

Upvotes: -5

Tara McGrew
Tara McGrew

Reputation: 2027

public void Foo<T>(T myParam)
    where T : IObject, ITreeNode<IObject>
{
    // whatever
}

Upvotes: 54

Anders Fjeldstad
Anders Fjeldstad

Reputation: 10814

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>.

Upvotes: 14

Related Questions