C# | Copying the HybridDictionary entries to an Array Instance (original) (raw)

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:

Below programs illustrate the use of HybridDictionary.CopyTo(Array, Int32) method:Example 1:

CSHARP `

// C# code to copy the HybridDictionary // entries to a one-dimensional Array // instance at the specified index. using System; using System.Collections; using System.Collections.Specialized;

class GFG {

// Driver code
public static void Main()
{

    // Creating a HybridDictionary named myDict
    HybridDictionary myDict = new HybridDictionary();

    // Adding key/value pairs in myDict
    myDict.Add("A", "Apple");
    myDict.Add("B", "Banana");
    myDict.Add("C", "Cat");
    myDict.Add("D", "Dog");
    myDict.Add("E", "Elephant");
    myDict.Add("F", "Fish");

    // Creating a one-dimensional Array named myArr
    DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];

    // copying the HybridDictionary entries
    // to a one-dimensional Array instance
    // at the specified index
    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:

CSHARP `

// C# code to copy the HybridDictionary // entries to a one-dimensional Array // instance at the specified index. using System; using System.Collections; using System.Collections.Specialized;

class GFG {

// Driver code
public static void Main()
{

    // Creating a HybridDictionary named myDict
    HybridDictionary myDict = new HybridDictionary();

    // Adding key/value pairs in myDict
    myDict.Add("I", "first");
    myDict.Add("II", "second");
    myDict.Add("III", "third");
    myDict.Add("IV", "fourth");
    myDict.Add("V", "fifth");

    // Creating a one-dimensional Array named myArr
    DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];

    // copying the HybridDictionary entries
    // to a one-dimensional Array instance
    // at the specified index
    // This should raise "ArgumentOutOfRangeException"
    // as index is less than 0
    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:

Reference: