Search code examples
c#genericsinterfacegeneric-programming

Why is this generic Interface definition wrong?


I am trying to write an interface that looks something like this

public interface IPropertyGroupCollection
{
    IEnumerable<IPropertyGroup> _Propertygroups { get;}
}

public interface IPropertyGroup
{
    IEnumerable<IProperty<T, U, V>> _conditions { get; }
}

public interface IProperty<T, U, V>
{
    T _p1 { get; }
    U _p2 { get; }
    V _p3 { get; }
}

public class Property<T, U, V> : IProperty<T, U, V>
{
    //Some Implementation
}

I keep on getting a compilation error for the ienumerable definition of _Conditions.

What am i doing wrong? The Idea is the implementing classes will serve a generic property bag collection


Solution

  • It's because you haven't declared T, U and V:

    public interface IPropertyGroup<T, U, V>
    {
        IEnumerable<IProperty<T, U, V>> _conditions { get; }
    }
    

    You will have to add generic types to IPropertyGroupCollection as well.

    Remember, IProperty<bool,bool,bool> is a different type to IProperty<int,int,int> despite the fact that they came from the same generic 'template'. You can't create a collection of IProperty<T, U, V>, you can only create a collection of IProperty<bool, bool, bool> or IProperty<int int, int>.

    UPDATE:

    public interface IPropertyGroupCollection
    {
        IEnumerable<IPropertyGroup> _Propertygroups { get;}
    }
    
    public interface IPropertyGroup
    {
        IEnumerable<IProperty> _conditions { get; }
    }
    
    public interface IProperty
    {
    }
    
    public interface IProperty<T, U, V> : IProperty
    {
        T _p1 { get; }
        U _p2 { get; }
        V _p3 { get; }
    }
    
    public class Property<T, U, V> : IProperty<T, U, V>
    {
        //Some Implementation
    }