SortedList.CopyTo(Array, Int32) Method is used to copy SortedList elements to a one-dimensional Array object, starting at the specified index in the array.
Syntax:
public virtual void CopyTo (Array array, int arrayIndex);
Parameters:
array: It is the one-dimensional Array object that is the destination of the DictionaryEntry objects copied from SortedList. The Array must have zero-based indexing.
arrayindex: It is the zero-based index in array at which copying begins.
Exceptions:
- ArgumentNullException: If the array is null.
- ArgumentOutOfRangeException: If the arrayindex is less than zero.
- ArgumentException: If the array is multidimensional or the number of elements in the source SortedList object is greater than the available space from arrayIndex to the end of the destination array.
- InvalidCastException: If the type of the source SortedList cannot be cast automatically to the type of the destination array.
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
class Geeks {
public static void Main(String[] args)
{
SortedList mylist = new SortedList();
mylist.Add( "1" , "C#" );
mylist.Add( "2" , "Java" );
mylist.Add( "3" , "DSA" );
mylist.Add( "4" , "Python" );
mylist.Add( "5" , "C" );
DictionaryEntry[] myArr = new DictionaryEntry[mylist.Count];
mylist.CopyTo(myArr, 0);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->" + myArr[i].Value);
}
}
}
|
Output:
1-->C#
2-->Java
3-->DSA
4-->Python
5-->C
Example 2:
using System;
using System.Collections;
class Geeks {
public static void Main(String[] args)
{
SortedList mylist = new SortedList();
mylist.Add( "1st" , "Ram" );
mylist.Add( "2nd" , "Shyam" );
mylist.Add( "3rd" , "Rohit" );
mylist.Add( "4th" , "Manish" );
mylist.Add( "5th" , "Vikas" );
DictionaryEntry[] myArr = new DictionaryEntry[mylist.Count];
mylist.CopyTo(myArr, -2);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->" + myArr[i].Value);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: arrayIndex
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!
Last Updated :
01 Feb, 2019
Like Article
Save Article