Lazycoder

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.

public struct Group { public string Name; public string Role; public Group(string name, string role) { this.Name = name; this.Role = role; } }

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));

  • David

    This is great – I was having exactly this problem. Thanks very much!

  • Adam Getchell

    Seconded! Great tip, solved my problem too!

  • Pingback: CodeBetter.Com Link Blog

  • Sonal

    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

  • Grant

    Thanks, exactly what i needed!

  • ramy dulman

    So simple, but yet so helpful.
    thx,
    ramy dulman.

  • Matthew

    That helped. Thanks for posting it.

  • Gary

    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!

  • Pingback: arraylist - StartTags.com

  • http://www.thecheapbags.com replica bags

    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.