C# ArrayList ToArray(Type)

Description

ArrayList ToArray(Type) copies the elements of the ArrayList to a new array of the specified element type.

Syntax

ArrayList.ToArray(Type) has the following syntax.


public virtual Array ToArray(
  Type type
)

Parameters

ArrayList.ToArray(Type) has the following parameters.

  • type - The element Type of the destination array to create and copy elements to.

Returns

ArrayList.ToArray(Type) method returns An array of the specified element type containing copies of the elements of the ArrayList.

Example

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


using System; //from  w w w  .  j ava2s. co  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