C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The string keyword is used, and not a string literal. Specifying types with "String Names" is less clear.
Main: The code populates a new ArrayList with 4 object instances containing string data (string literals).
Cast: The as-cast is necessary to use strong typing on the result from ToArray. It will result in a null value if the cast does not succeed.
AsNullC# program that converts an ArrayList
using System;
using System.Collections;
class Program
{
static void Main()
{
//
// Create an ArrayList with 4 strings.
//
ArrayList list = new ArrayList();
list.Add("flora");
list.Add("fauna");
list.Add("mineral");
list.Add("plant");
//
// Convert ArrayList to array.
//
string[] array = list.ToArray(typeof(string)) as string[];
//
// Loop over array.
//
foreach (string value in array)
{
Console.WriteLine(value);
}
}
}
Output
flora
fauna
mineral
plant
Tip: This provides superior performance over manually copying elements in your C# program.