Convert an ArrayList into an array : ArrayList ToArray « Data Structure « C# / CSharp Tutorial






using System; 
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    // Add elements to the array list. 
    al.Add(1); 
    al.Add(2); 
    al.Add(3); 
    al.Add(4); 
 
    Console.Write("Contents: "); 
    foreach(int i in al) 
      Console.Write(i + " "); 
    Console.WriteLine(); 
 
    // Get the array. 
    int[] ia = (int[]) al.ToArray(typeof(int)); 
    int sum = 0; 
 
    // sum the array 
    for(int i=0; i<ia.Length; i++) 
      sum += ia[i]; 
 
    Console.WriteLine("Sum is: " + sum); 
  } 
}
Contents: 1 2 3 4
Sum is: 10








11.24.ArrayList ToArray
11.24.1.Convert an ArrayList into an array
11.24.2.Use ArrayList.ToArray to create a strongly typed string array from the contents of the collection
11.24.3.Convert user-defined objects in an ArrayList to an array