Convert user-defined objects in an ArrayList to an array : ArrayList ToArray « Data Structure « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Collections.Specialized;

class MyClass{
   public string MyName="";   
}

class MainClass
{
  static void Main(string[] args)
  {
    ArrayList classList = new ArrayList();
    classList.AddRange(new MyClass[] { new MyClass(), 
                                           new MyClass(), 
                                           new MyClass()});
    Console.WriteLine("Items in List: {0}", classList.Count);

       // Get object array from ArrayList & print again.
    object[] arrayOfMyClasss = classList.ToArray();
    for(int i = 0; i < arrayOfMyClasss.Length; i++)
    {
      Console.WriteLine("MyClass name: {0}", 
        ((MyClass)arrayOfMyClasss[i]).MyName);
    }

  }
}
Items in List: 3
MyClass name:
MyClass name:
MyClass name:








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