How make a collection of type which is generic type in c#

65 Views Asked by At

I have class like the following

public class Relation<T1, T2> where T1: Entity where T2: Entity
{
}

I want to make class derived from a list/collection which is of the type Relation

public class RelationList<T>: List<Relation>> 
{

}

I have tried in SO but couldn't get things right. Even right pointer to SO will also help

1

There are 1 best solutions below

1
MarcinJuraszek On BEST ANSWER

Because your Relation class is generic you have to specify generic types when you derive from Relation.

Either as

public class RelationList: List<Relation<MyEntity2, MyEntity2>>
{
}

or as

public class RelationList<T1, T2> : List<Relation<T1, T2>> 
        where T1: Entity
        where T2: Entity
{
}

If you want RelationList to be able to keep Relation<T1, T2> no matter how T1 and T2 is specified you should use additional interface:

public interface IRelation
{
}

public class Relation<T1, T2> : IRelation
    where T1: Entity where T2: Entity
{
}

public class RelationList : List<IRelation>
{
}