views:

294

answers:

2

I'm trying to create the extension method AddRange for HashSet so I can do something like this:

var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);

This is what I have so far:

public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
    foreach (var item in list)
    {
        collection.Add(item);
    }
}

Problem is, when I try to use AddRange, I'm getting this compiler error:

The type arguments for method 'AddRange<T>(System.Collections.Generic.ICollection<T>, System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

In other words, I have to end up using this instead:

hashset.AddRange<Item>(list);

What am I doing wrong here?

A: 

Your code works fine for me:

using System.Collections.Generic;

static class Extensions
{
    public static void AddRange<T>(this ICollection<T> collection, List<T> list)
    {
        foreach (var item in list)
        {
            collection.Add(item);
        }
    }
}

class Item {}

class Test
{
    static void Main()
    {
        var list = new List<Item>{ new Item(), new Item(), new Item() };
        var hashset = new HashSet<Item>();
        hashset.AddRange(list);
    }
}

Could you give a similar short but complete program which fails to compile?

Jon Skeet
I figured out the problem, but it was unrelated to the extension method. Rather, I was trying to implicitly cast a List to a HashSet, which didn't work and caused the extension method to be unable to implicitly cast it as well.
Daniel T.
+2  A: 

Use hastset.UnionWith(list);

JDT