views:

149

answers:

3

I try to do static class, add to icollection but i got some issues i cant seem to overcome. that is how i get so i can pass a ICollection in the method? cause T is that say it can not be resolved.

and then i wonder is there a way to do AddRange on icollection?

i was thinking of something like this but maby i am way out of my mind with it?

public static ICollection<T> add(this IEnumerable<T> list)
    {
        ICollection<T> collection = null;

        return collection.AddRange(list);            
    }
A: 
public static ICollection<T> add<T>(this IEnumerable<T> list)
{
  var collection = new List<T>();
  collection.AddRange(list);
  return collection;
}
leppie
+4  A: 

No, ICollection<T> doesn't have an AddRange method - and even if it did, you'd be trying to dereference null which will throw a NullReferenceException. You haven't specified a collection to add the list to... what exactly are you trying to do?

You could create (say) a new List<T> - and that has the benefit of already having a constructor which can take an IEnumerable<T>:

public static ICollection<T> Add<T>(this IEnumerable<T> list)
{
    return new List<T>(list);            
}

However, at that point you've really just reimplemented Enumerable.ToList() and given it a different return type...

If you want to add everything to an existing collection, you might want something like this:

public static ICollection<T> AddTo<T>(this IEnumerable<T> list,
                                      ICollection<T> collection)
{
    foreach (T item in list)
    {
        collection.Add(item);
    }
    return collection;
}
Jon Skeet
Love the new name...had no idea who it was either. :-P
Justin Niessner
You are missing a generic method argument :)
leppie
@leppie: Just spotted that in an edit.
Jon Skeet
Or even better, just call the existing .ToList() method...
Joel Coehoorn
@Joel: Hence "at that point you've really just reimplemented Enumerable.ToList() and given it a different return type..." :)
Jon Skeet
great post. i learned some new things here
Dejan.S
+2  A: 

If I understand correctly you want to add a IEnumerable<T> to an empty collection.

Wouldn't it be easier to just do:

ICollection<MyObject> collection = new List<MyObject>(GetIEnumerableOfMyObject());

Or even:

ICollection<MyObject> collection = GetIEnumerableOfMyObject().ToList();
Yannick M.
i did not know i could do a ICollection then do the list like that.
Dejan.S
`List<T>` implements `ICollection<T>` so yup.
Yannick M.