ToArray(Type) method in ArrayList
In this article I will discuss the ToArray(Type) method of ArrayList.
Introduction
ToArray(Type) method of ArrayList copies the elements of the ArrayList to a new array of the specified element type.For example If we want to copy the arraylist into the array then this method ToArray is used.
Example
public class MyArrayList
{
public static void Main()
{
// Creates a new ArrayList.
ArrayList myArray = new ArrayList();
myArray.Add("one");
myArray.Add("two");
myArray.Add("three");
myArray.Add("four");
myArray.Add("five");
myArray.Add("six");
myArray.Add("seven");
myArray.Add("eight");
myArray.Add("nine");
myArray.Add("ten");
// Displays the values of the ArrayList.
Console.WriteLine("The ArrayList contains the following values:");
foreach (string s in myArray)
{
Console.WriteLine(s);
}
// Copies the elements of the ArrayList to a string array.
String[] myArr = (String[])myArray.ToArray(typeof(string));
// Displays the contents of the string array.
Console.WriteLine("The string array contains the following values:");
foreach (string s in myArr)
{
Console.WriteLine(s);
}
}
}
|
Output
Ask Your Question
Got a programming related question? You may want to post your question here