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);
I'm surprised that
Array array = new Array[list.Count];
even compiles but it does not do what you want it to. Use
object[] array = new object[list.Count];
And, standard remark: if you can use C#3 or later, avoid ArrayList as much as possible. You'll probably be happier with a List<int>
probably the most compact solution is this:
Enumerable.Range(0, list.Count).Select(i => list[i]).ToArray();
You can use Cast and ToArray:
Array array = list.Cast<int>().ToArray();
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.