Search code examples
c#interfacecomposition

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


Solution

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