I have a generic collection looking like this
Set<T> : ICollection<T>
{
// Create set from existing collection.
public Set(ICollection<T> objs) {/* */}
// Add objects to set
public void AddRange(ICollection<T> objs){ /* */ }
}
Now, say I want to create a set for a general type and keep more
specific types in it:
Set<Fruit> fruits = new Set<Fruits>()
List<Fruit> fruitList = new List<Fruit>();
List<Apple> appleList = new List<Apple>();
fruits.AddRange(fruitList); // This is ok of course
fruits.AddRange(appleList); // This is not
This problem can be fixed by modifying the Add() method of my
collection to this
public void AddRange<U>(ICollection<U> obj) where U : T { /* */ }
Now I can do an AddRange(appleList).
So my question, is there any way to have a similar constraint in the
constructor?
class Set<T> : ICollection<T>
{
// Create set from existing collection.
public Set(ICollection<U> objs) : where U : T {/* *}
}
That would allow for this:
List<Apple> apples = new List<Apple>();
Set<Fruit> fruits = new Set(apples);
Thanks