The problem of getting the correct extension method

I am trying to create an AddRange extension method for a 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);
    }
}

      

The problem is that when I try to use AddRange I get 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 use this instead:

hashset.AddRange<Item>(list);

      

What am I doing wrong here?

+2


source to share


2 answers


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 please give a similarly short but complete program that won't compile?

+3


source


Use



hashSet.UnionWith<Item>(list);

      

+30


source







All Articles