C# | How to convert an ArrayList to Array
Last Updated :
03 Jun, 2021
In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It allows dynamic memory allocation, adding, searching and sorting items in the list.
Below are the two methods for converting an ArrayList to an Array:
Method 1: Convert an ArrayList to Array of object
Syntax:
public virtual object[] ToArray ();
Explanation:
- It copy the elements of the ArrayList to a new Object array.
- It return an Object array containing copies of the elements of the ArrayList.
Example: In the below program, mylist is the ArrayList and we added 7 items to it which are the name of weekdays. Then we are creating an object array obj1 and using ToArray method with mylist we will assign the Arraylist elements to the object array. Finally, using foreach loop you can print the required converted array.
CSharp
// C# program to illustrate ToArray() Method
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main()
{
// Create and initializing ArrayList
ArrayList mylist = new ArrayList(7);
mylist.Add("Monday");
mylist.Add("Tuesday");
mylist.Add("Wednesday");
mylist.Add("Thursday");
mylist.Add("Friday");
mylist.Add("Saturday");
mylist.Add("Sunday");
// Copy the data of Arraylist into
// the object Array Using ToArray()
// method
object[] obj1 = mylist.ToArray();
foreach(string st in obj1)
{
Console.WriteLine(st);
}
}
}
Output: Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Method 2: Convert An ArrayList to Array of specified type
Syntax:
public virtual Array ToArray (Type t);
Here, t is the element Type of the destination array to create and copy elements.
Explanation:
- It copy the elements of the ArrayList to a new array of the specified element type.
- It return an array of the specified element type containing copies of the elements of the ArrayList.
- It throws ArgumentNullException if the value of t is null.
- It throws InvalidCastException if the type of the source ArrayList cannot be cast automatically to the specified type.
Example 1:
CSharp
// C# program to illustrate the use
// of ToArray(Type) Method in the
// conversion of ArrayList to Array
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main()
{
// Create and initialize new array
ArrayList mylist = new ArrayList(5);
mylist.Add("Ruby");
mylist.Add("C#");
mylist.Add("C++");
mylist.Add("Java");
mylist.Add("Perl");
// Copy the data of Arraylist into
// the string Array Using
// ToArray(Type) method
string[] str = (string[])mylist.ToArray(typeof(string));
// Display the data of str string
foreach(string j in str)
{
Console.WriteLine(j);
}
}
}
Output: Ruby
C#
C++
Java
Perl
Explanation of Code: Here, we are converting an ArrayList to Array of specified type i.e string type. For conversion, you have to use ToArray(Type) method along with typeof keyword. And then you have to explicitly cast it to the specified type. Here you can see the line of code, string[] str = (string[])mylist.ToArray(typeof(string));. (string[]) is used for mylist to convert it to string array type. There is another alternative for this line of code as shown in below example.
Example 2:
CSharp
// C# program to illustrate the use
// of ToArray(Type) Method in the
// conversion of ArrayList to Array
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main()
{
// Create and initialize new array
ArrayList mylist = new ArrayList(5);
mylist.Add("Ruby");
mylist.Add("C#");
mylist.Add("C++");
mylist.Add("Java");
mylist.Add("Perl");
// Copy the data of Arraylist into
// the string Array Using
// ToArray(Type) method
// see this clearly as here we
// are using as keyword
string[] str = mylist.ToArray(typeof(string)) as string[];
// Display the data of str string
foreach(string j in str)
{
Console.WriteLine(j);
}
}
}
Output: Ruby
C#
C++
Java
Perl
What will happen if the ArrayList doesn't contain all the elements of the same type?
If the ArrayList doesn't contain the elements of the same type then your conversion(ArrayList to Array) will throw InvalidCastException.
Example:
CSharp
// C# program to illustrate the use
// of ToArray(Type) Method in the
// conversion of ArrayList to Array
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main()
{
// Create and initialize new array
ArrayList mylist = new ArrayList(5);
mylist.Add("Ruby");
mylist.Add(5);
mylist.Add("C++");
mylist.Add(7);
mylist.Add("Perl");
// It will throw the InvalidCastException
// Copy the data of Arraylist into
// the string Array Using
// ToArray(Type) method
string[] str = mylist.ToArray(typeof(string)) as string[];
// Display the data of str string
foreach(string j in str)
{
Console.WriteLine(j);
}
}
}
Runtime Error:
Unhandled Exception:
System.InvalidCastException: Specified cast is not valid.
Similar Reads
C# | Copying the elements of ArrayList to a new array
ArrayList.ToArray Method is used to copy the elements of the ArrayList to a new array. This method contains two methods in its overload list as follows: ToArray()ToArray(Type)ToArray() This method is used to copy the elements of the ArrayList to a new Object array. The elements are copied using Arra
2 min read
C# | How to copy the entire ArrayList to a one-dimensional Array
ArrayList.CopyTo Method is used to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array. Syntax: public virtual void CopyTo (Array array); Here, array is the one-dimensional Array which is the destination of the elements copied from ArrayList
3 min read
How to create the ArrayList in C#
ArrayList() constructor is used to initialize a new instance of the ArrayList class which will be empty and will have the default initial capacity. ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dyn
2 min read
C# | Array vs ArrayList
Arrays: An array is a group of like-typed variables that are referred to by a common name. Example: CSHARP // C# program to demonstrate the Arrays using System; class GFG { // Main Method public static void Main(string[] args) { // creating array int[] arr = new int[4]; // initializing array arr[0]
2 min read
C# | Convert Stack to array
Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.ToArray Method is used to copy a Stack<T
2 min read
C# | Add an object to the end of the ArrayList
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Add(Object) method adds an object to the end of the ArrayList. Pr
2 min read
C# | Converting an array of one type to an array of another type
Array.ConvertAll(TInput[], Converter<TInput, TOutput>) Method is used to convert an array of one type to an array of another type. Syntax: public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, Converter<TInput,TOutput> converter); Here, TInput and TOutput is the sourc
3 min read
C# | Convert Queue To array
Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue.ToArray Method is used to copy the Queue elements to a new array
2 min read
C# | Copy the Stack to an Array
Stack<T>.CopyTo(T[], Int32) Method is used to copy the Stack<T> to an existing 1-D Array which starts from the specified array index. Properties: The capacity of a Stack<T>is the number of elements the Stack<T> can hold. As elements are added to a Stack<T> , the capacit
2 min read
C# | Getting an enumerator for the entire ArrayList
ArrayList.GetEnumerator Method is used to get an enumerator for the entire ArrayList. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (); Return Value: It returns an IEnumerator for the entire ArrayList. Below programs illustrate the use of above-discussed method: Example 1: CSha
2 min read