Arraylist.ToArray
The ArrayList class in the System.Collections namespace is a handy class to have around when you have to put objects into an array but you don’t have any idea how many objects you have. There is a hitch when you want to convert the ArrayList to an Array using the ToArray method.
Say you have a struct like this.
And you want to create an array of this struct. That's easy enough to do by defining your variable like so:
Group [] oGroups = new Group[2];
but what if you don't know how many Group structs you will need ahead of time? You can use an Array list to hold the values and dynamically resize the ArrayList.
ArrayList listGroups = new ArrayList();
//drGroups is a DataReader object
while(drGroups.Read())
{
listGroups.Add(new Group(drGroups["GroupName"].ToString(),drGroups["RoleName"].ToString()));
}
That's ok, but now you have an ArrayList, not an array of type "Group". Luckily you can use the ToArray() method of the ArrayList class to convert it to a Group array. There is a catch though. Even though you pass in a type ("Group") it returns an array of objects. You need to explicitly cast it as the type you want the array to be of.
arGroups = (Group[]) listGroups.ToArray(typeof(Group));

March 23rd, 2005 - 09:39
This is great – I was having exactly this problem. Thanks very much!
April 7th, 2005 - 15:43
Seconded! Great tip, solved my problem too!
April 21st, 2005 - 03:53
Hi,
Even i am facing the same problem. If i give
CustomerProfile []CPLifestyleArray = (CustomerProfile [])arrLS.toArray();
it gives class cas exception and if i give:
CustomerProfile []CPLifestyleArray = (CustomerProfile [])arrLS.toArray(typeof(CustomerProfile));
it gives error of variable CustomerProfile.
Could anyone please tell me the reason?
Thanks in advance,
sonal
May 24th, 2005 - 04:34
Thanks, exactly what i needed!
June 8th, 2005 - 04:19
So simple, but yet so helpful.
thx,
ramy dulman.
August 9th, 2005 - 15:19
That helped. Thanks for posting it.
September 14th, 2005 - 20:21
Thank you so much. When I saw your example I realized I was casting the array from ToArray() as my custom type rather than an array of my custom type. Duh!
July 29th, 2010 - 01:08
LuaJIT seems to do very well in the game of language benchmarks, but those seem rather un-realistic at times. I mean I would consider anything related to closures much more important (speed-wise), than any raw number crunching.