C# ArrayList ToArray()

Description

ArrayList ToArray() copies the elements of the ArrayList to a new Object array.

Syntax

ArrayList.ToArray() has the following syntax.


public virtual Object[] ToArray()

Returns

ArrayList.ToArray() method returns

Example

The following code demonstrates the following methods: CopyTo(), ToArray(), ToArray(typeof(String)).


using System; // ww w . j a v  a 2s .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(s);
        }
        foreach (string s in array2)
        {
            Console.WriteLine(s);
        }
        foreach (string s in array3)
        {
            Console.WriteLine(s);
        }
     }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections »




ArrayList
BitArray
Comparer
Hashtable
Queue
SortedList
Stack