Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from Array to ICollection<T>

Tags:

c#

What is the best way to accomplish this in C#?

like image 834
LB. Avatar asked Oct 27 '09 12:10

LB.


3 Answers

Arrays of T are assignable to ICollection of T, as an array of T implements IList of T. IList of T itself extends ICollection of T, so you can simply assign an array to an ICollection.

class Foo {}

Foo [] foos = new Foo [12];
ICollection<Foo> foo_collection = foos;
like image 189
Jb Evain Avatar answered Oct 12 '22 17:10

Jb Evain


Short answer:

Use ToList(). Don't rely on T[] being assignable to ICollection<T> unless you are aware of the following and know what you're doing.

If you need it read-only, it's better to use Array.AsReadOnly(T[]) and avoid the extra copy, and also avoid the problems detailed below.


Detailed answer:

Although array of T (ie. T[]) technically implements IList<T> (and ICollection<T> and IEnumerable<T>), it does not actually implement the entire IList<T> and ICollection<T> interfaces, as mentioned in the documentation:

...The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

In other words, if you just cast the array to ICollection<T> you will get NotSupportedException as soon as you call any of the aforementioned methods.

So the best way to convert an array safely to an ICollection<T> would be to create a new object, such as using Linq's ToList():

T[] array;

// Will create a new list based on the current contents of the array
ICollection<T> collection = array.ToList();
like image 23
sinelaw Avatar answered Oct 12 '22 17:10

sinelaw


In addition to the answer and the comment, if you want to go the other way, you use the ToArray() method on IEnumerable<T> (which ICollection<T> descends from).

like image 25
Jesse C. Slicer Avatar answered Oct 12 '22 19:10

Jesse C. Slicer