Subscribe

RSS Feed (xml)

Copy a Collection to an Array

The ICollection.CopyTo method and the ToArray method perform roughly the same function—they perform a shallow copy of the elements contained in a collection to an array. The key difference is that CopyTo copies the collection's elements to an existing array, whereas ToArray creates a new array before copying the collection's elements into it.
The CopyTo method takes two arguments: an array and an index. The array is the target of the copy operation and must be of a type appropriate to handle the elements of the collection. If the types don't match or there is no implicit conversion possible from the collection element's type to the array element's type, a System.InvalidCastException is thrown. The index is the starting element of the array where the collection's elements will be copied. If the index is equal to or greater than the length of the array, or the number of collection elements exceeds the capacity of the array, a System.ArgumentException is thrown. This code excerpt shows how to copy the contents of an ArrayList to an array using the CopyTo method.
// Create a new ArrayList and populate it.
ArrayList list = new ArrayList(5);
list.Add("Brenda");
list.Add("George");
list.Add("Justin");
list.Add("Shaun");
list.Add("Meaghan");

// Create a string[] and use the ICollection.CopyTo method to 
// copy the contents of the ArrayList.
string[] array1 = new string[5];
list.CopyTo(array1,0);        
The ArrayList, Stack, and Queue classes also implement the ToArray method, which automatically creates an array of the correct size to accommodate a copy of all the elements of the collection. If you call ToArray with no arguments, it returns an object[] regardless of the type of objects contained in the collection. However, you can pass a System.Type object that specifies the type of array that the ToArray method should create. (You must cast the returned strongly typed array to the correct type.) Here is an example of how to use the ToArray method on the ArrayList created in the previous listing.
// Use ArrayList.ToArray to create an object[] from the contents
// of the collection.
object[] array2 = list.ToArray();

// Use ArrayList.ToArray to create a strongly typed string[] from 
// the contents of the collection.
string[] array3 = 
    (string[])list.ToArray(System.Type.GetType("System.String"));

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail