Open In App

C# | Copy StringCollection at the specified index of array

StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.

StringCollection.CopyTo(String[], Int32) method is used to copy the entire StringCollection values to a one-dimensional array of strings which starts at the specified index of the target array.



Syntax:

public void CopyTo (string[] array, int index);

Parameters:



Exceptions:

Note:

Below given are some examples to understand the implementation in a better way:

Example 1:




// C# code to copy StringCollection to array,
// starting at the specified index of
// the target array
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr1
        String[] myArr1 = new String[] { "A", "B", "C", "D", "E" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr1);
  
        // creating a String array named myArr2
        String[] myArr2 = new String[myCol.Count];
  
        // Copying StringCollection to array myArr2
        // starting from index 0
        myCol.CopyTo(myArr2, 0);
  
        // Displaying elements in array myArr2
        for (int i = 0; i < myArr2.Length; i++) {
            Console.WriteLine(myArr2[i]);
        }
    }
}

Output:

A
B
C
D
E

Example 2:




// C# code to copy StringCollection to array,
// starting at the specified index of
// the target array
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr1
        String[] myArr1 = new String[] {"1", "2", "3",
                                       "4", "5", "6"};
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr1);
  
        // creating a String array named myArr2
        String[] myArr2 = new String[myCol.Count];
  
        // Copying StringCollection to array myArr2
        // starting from index -1
        // This should raise exception "ArgumentOutOfRangeException"
        // as index is less than 0
        myCol.CopyTo(myArr2, -1);
  
        // Displaying elements in array myArr2
        for (int i = 0; i < myArr2.Length; i++) {
            Console.WriteLine(myArr2[i]);
        }
    }
}

Output:

Unhandled Exception:
System.ArgumentOutOfRangeException: Value has to be >= 0.
Parameter name: destinationIndex

Reference:


Article Tags :
C#