Skip to content

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