Copying the elements of ArrayList to a new array in C#

CsharpServer Side ProgrammingProgramming

To copy the elements of ArrayList to a new array, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList(10);
      list.Add("A");
      list.Add("B");
      list.Add("C");
      list.Add("D");
      list.Add("E");
      list.Add("F");
      list.Add("G");
      list.Add("H");
      list.Add("I");
      list.Add("J");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in list){
         Console.WriteLine(str);
      }
      Console.WriteLine("Array elements copied from ArrayList...");
      object[] ob = list.ToArray();
      foreach(string str in ob){
         Console.WriteLine(str);
      }
   }
}

Output

This will produce the following output −

ArrayList elements...
A
B
C
D
E
F
G
H
I
J
Array elements copied from ArrayList... A
B
C
D
E
F
G
H
I
J

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList(10);
      list.Add(100);
      list.Add(200);
      list.Add(300);
      Console.WriteLine("ArrayList elements...");
      foreach(int val in list){
         Console.WriteLine(val);
      }
      Console.WriteLine("Array elements copied from ArrayList...");
      object[] ob = list.ToArray();
      foreach(int val in ob){
         Console.WriteLine(val);
      }
   }
}

Output

This will produce the following output −

ArrayList elements...
100
200
300
Array elements copied from ArrayList... 100
200
300
raja
Published on 10-Dec-2019 11:07:25
Advertisements