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);
}
No,
ICollection<T>
doesn't have anAddRange
method - and even if it did, you'd be trying to dereferencenull
which will throw aNullReferenceException
. 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 anIEnumerable<T>
: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:
The other ways seem to assume that your ICollection is empty and/or your ICollection is a type of List. However, if you want AddRange, then you can Extend the ICollection class as follows:
Note, however, that since List impliments ICollection, this may cause ambiguity when dealing directly with List objects (though I haven't tested yet if the compiler will be able to resolve it--my gut reaction is that it should, though, since AddRange is a member of List and the compiler will go through member functions first before looking at extensions, but if I'm wrong I'm sure someone will correct me).
If I understand correctly you want to add a
IEnumerable<T>
to an empty collection.Wouldn't it be easier to just do:
Or even:
Depending on the collection type of your source list an alternative approach is to use
List(T).ForEach
, as in:However, the readability of this is easy to dispute.