StringDictionary.CopyTo(Array, Int32) method is used to copy the string dictionary values to a one-dimensional Array instance at the specified index.
Syntax:
public virtual void CopyTo (Array array, int index);
Parameters:
- array: It is the one-dimensional Array which is the destination of the values copied from the StringDictionary.
- index: It is the index in the array where copying begins.
Exceptions:
- ArgumentNullException : If the key is null.
- ArgumentOutOfRangeException : If the index is less than the lower bound of array.
- ArgumentException : If the array is multidimensional Or the number of elements in the StringDictionary is greater than the available space from index to the end of array.
Below programs illustrate the use of StringDictionary.CopyTo(Array, Int32) method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
myDict.Add( "E" , "Elephant" );
DictionaryEntry[] myArr = { new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry() };
myDict.CopyTo(myArr, 0);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + " " + myArr[i].Value);
}
}
}
|
Output:
d Dog
b Banana
c Cat
e Elephant
a Apple
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
myDict.Add( "E" , "Elephant" );
DictionaryEntry[] myArr = { new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry() };
myDict.CopyTo(myArr, 0);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + " " + myArr[i].Value);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentException: Destination array is not long enough to copy all the items in the collection. Check array index and length.
Note:
- The elements copied to the Array are sorted in the same order that the enumerator iterates through the StringDictionary.
- This method is an O(n) operation, where n is Count.
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