C# | Copying the HybridDictionary entries to an Array Instance
Last Updated :
01 Feb, 2019
HybridDictionary.CopyTo(Array, Int32) method is used to copy the HybridDictionary entries to a one-dimensional Array instance at the specified index.
Syntax:
public void CopyTo (Array array, int index);
Parameters:
array : The one-dimensional Array that is the destination of the DictionaryEntry objects copied from HybridDictionary. The Array must have zero-based indexing.
index : The zero-based index in array at which copying begins.
Exceptions:
- ArgumentNullException : If the array is null.
- ArgumentOutOfRangeException : If the index is less than zero.
- InvalidCastException : If the type of the source HybridDictionary cannot be cast automatically to the type of the destination array.
- ArgumentException : If array is multidimensional OR the number of elements in the source HybridDictionary is greater than the available space from arrayIndex to the end of the destination array.
Below programs illustrate the use of HybridDictionary.CopyTo(Array, Int32) method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
HybridDictionary myDict = new HybridDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
myDict.Add( "E" , "Elephant" );
myDict.Add( "F" , "Fish" );
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
myDict.CopyTo(myArr, 0);
for ( int i = 0; i < myArr.Length; i++)
Console.WriteLine(myArr[i].Key + " --> "
+ myArr[i].Value);
}
}
|
Output:
A --> Apple
B --> Banana
C --> Cat
D --> Dog
E --> Elephant
F --> Fish
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
HybridDictionary myDict = new HybridDictionary();
myDict.Add( "I" , "first" );
myDict.Add( "II" , "second" );
myDict.Add( "III" , "third" );
myDict.Add( "IV" , "fourth" );
myDict.Add( "V" , "fifth" );
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
myDict.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: Index is less than zero.
Parameter name: index
Note:
- The elements are copied to the Array in the same order in which the enumerator iterates through the HybridDictionary.
- To copy only the keys in the HybridDictionary, use HybridDictionary.Keys.CopyTo.
- To copy only the values in the HybridDictionary, use HybridDictionary.Values.CopyTo.
- This method is an O(n) operation, where n is Count.
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...