Reputation: 38390
I have the following extension method to add the elements in one collection to another collection:
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
This works fine if the IEnumerable list is the same type as the ICollection I'm trying to add it to. However, if I have something like this:
var animals = new List<Animal>();
var dogs = new List<Dog>(); // dog is a subclass of animal
animals.AddRange(dogs); // this line has a compiler error, it can't infer the type
How do I modify my extension method to be able to do something like this, if the type of the IEnumerable is a subclass (or implements the interface) of the T type?
Upvotes: 2
Views: 2833
Reputation: 3155
wait for C# 4.0 or use the Linq extension method Cast
:
List<Animal> animals = new List<Animal>();
List<Dog> dogs = new List<Dog>();
animals.AddRange(dogs.Cast<Animal>());
Upvotes: 1
Reputation: 41096
public static void AddRange<TA, TB>(this ICollection<TA> collection,
IEnumerable<TB> list) where TB : TA
(incorporated Craig Walker's comment)
Upvotes: 0
Reputation: 15658
I would use constraint to restrict the type.
public static void AddRange<T, TK>(this ICollection<T> collection, IEnumerable<TK> list) where TK : T
{
foreach (var item in list)
{
collection.Add(item);
}
}
Upvotes: 0
Reputation: 51717
This method will give you what you want:
public static void AddRange<A,B>(
this ICollection<A> collection,
IEnumerable<B> list)
where B: A
{
foreach (var item in list)
{
collection.Add(item);
}
}
A couple of notes:
Upvotes: 5
Reputation: 10650
You can do this:
public static void AddRange<T,T2>(this ICollection<T> collection, IEnumerable<T2> list) where T2: T {
foreach (var item in list) {
collection.Add(item);
} }
Upvotes: 2