Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Convert ArrayList to Array

This C# program converts an ArrayList to an array. It uses the ToArray method.

Convert ArrayList, array. An ArrayList has similarities to an array.

It stores a one-dimensional collection of elements. It can be converted to an array with the ToArray method. ToArray is found on the ArrayList type.


Example. You will need to provide a Type parameter to the ToArray method on ArrayList. This is because otherwise the method would not know what type to convert each element to. Here we do that with the typeof operator.


Note: The string keyword is used, and not a string literal. Specifying types with "String Names" is less clear.

C# 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();
	// Convert ArrayList to array.
	string[] array = list.ToArray(typeof(string)) as string[];
	// Loop over array.
	foreach (string value in array)



The code defines the Main entry point and then populates a new ArrayList with four object instances containing string data (string literals). In this example, the strings are interned by the runtime, so share memory.

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. In some programs, it is best to check for null.


Internals. When we open up the ToArray instance method in IL Disassembler, we see that this method (along with the CopyTo method) calls into the Array.Copy method. Array.Copy uses an external, native-code implementation.


Tip: This provides superior performance over manually copying elements in your C# program.

Summary. We used the ArrayList's ToArray method to convert the contents of an ArrayList to a string array. The example here can be adapted to other reference and value types. We also looked inside the base class library.

Convert ArrayList to List

Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf