Copy a Collection to an Array - CSharp Collection

CSharp examples for Collection:ArrayList

Description

Copy a Collection to an Array

Demo Code

using System;//from   w ww  .j  a v  a2s  .c o m
using System.Collections;
class MainClass
{
   public static void Main()
   {
      ArrayList list = new ArrayList(5);
      list.Add("B");
      list.Add("G");
      list.Add("J");
      list.Add("S");
      list.Add("M");
      string[] array1 = new string[list.Count];
      list.CopyTo(array1, 0);
      object[] array2 = list.ToArray();
      string[] array3 = (string[])list.ToArray(typeof(String));
      foreach (string s in array1){
         Console.WriteLine("\t{0}",s);
      }
      foreach (string s in array2){
         Console.WriteLine("\t{0}", s);
      }
      foreach (string s in array3){
         Console.WriteLine("\t{0}", s);
      }
   }
}

Result


Related Tutorials