Convert an ArrayList into an array : ArrayList ToArray : Data Structure C# Examples


C# Examples » Data Structure » ArrayList ToArray »

 

Convert an ArrayList into an array









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



Output

Contents: 1 2 3 4
Sum is: 10


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Data Structure
» ArrayList ToArray