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 Array.Copy, which is an O(n) operation, where n is Count.
Syntax:
public virtual object[] ToArray ();
Return Value: This method will return an Object array containing copies of the elements of the ArrayList.
Example:
CSharp
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList mylist = new ArrayList(5);
mylist.Add( "G" );
mylist.Add( "E" );
mylist.Add( "E" );
mylist.Add( "K" );
mylist.Add( "S" );
object [] str2 = mylist.ToArray();
foreach ( string i in str2)
{
Console.WriteLine(i);
}
}
}
|
ToArray(Type)
This method is used to copy the elements of the ArrayList to a new array of the specified element type. The elements are copied using Array.Copy, which is an O(n) operation, where n is Count.
Syntax:
public virtual Array ToArray (Type t);
Here, t is the element Type of the destination array to create and copy elements to.
Return Value : This method will return an array of the specified element type containing copies of the elements of the ArrayList.
Exception:
- If the value of t is null then this method will give ArgumentNullException.
- If the type of the source ArrayList cannot be cast automatically to the specified type, then this method will give InvalidCastException.
Note: All of the objects in the ArrayList object will be cast to the Type specified in the type parameter.
Example:
CSharp
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList mylist = new ArrayList(5);
mylist.Add( "G" );
mylist.Add( "E" );
mylist.Add( "E" );
mylist.Add( "K" );
mylist.Add( "S" );
string [] str2 = ( string [])mylist.ToArray( typeof ( string ));
foreach ( string i in str2)
{
Console.WriteLine(i);
}
}
}
|
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!