Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IList to array in C#

I want to convert IList to array: Please see my code:

IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);

Why I get System.InvalidCastException : At least one element in the source array could not be cast down to the destination array type? How that can be resolved assuming I can not use ArrayList as type for list variable ?

Update 1: I use .NET 1.1. So I can not use Generics, Linq and so on. I just want to receive result for the most common case - integer was given as example, I need this code works for all types so I use Array here (maybe I am wrong about using Array but I need, once again, common case).

like image 569
Michael Z Avatar asked Feb 29 '12 21:02

Michael Z


People also ask

How to convert IList to array?

IList list = new ArrayList(); list. Add(1); Array array = new Array[list. Count]; list. CopyTo(array, 0);

Is an array an IList?

Definition of IList interface is "Represents a non-generic collection of objects that can be individually accessed by index.". Array completely satisfies this definition, so must implement the interface.


1 Answers

You're creating an array of Array values. 1 is an int, not an Array. You should have:

IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);

or, ideally, don't use the non-generic types to start with... use List instead of ArrayList, IList<T> instead of IList etc.

EDIT: Note that the third line could easily be:

Array array = new object[list.Count];

instead.

like image 137
Jon Skeet Avatar answered Oct 17 '22 20:10

Jon Skeet