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:
- array : It is the one-dimensional array of strings that is the destination of the elements copied from StringCollection. The Array must have zero-based indexing.
- index : It is 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 StringCollection cannot be cast automatically to the type of the destination array.
- ArgumentException : If the array is multidimensional or the number of elements in the source StringCollection is greater than the available space from index to the end of the destination array.
Note:
- The specified array must be of a compatible type.
- This method is an O(n) operation, where n is Count.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr1 = new String[] { "A" , "B" , "C" , "D" , "E" };
myCol.AddRange(myArr1);
String[] myArr2 = new String[myCol.Count];
myCol.CopyTo(myArr2, 0);
for ( int i = 0; i < myArr2.Length; i++) {
Console.WriteLine(myArr2[i]);
}
}
}
|
Output:
A
B
C
D
E
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr1 = new String[] { "1" , "2" , "3" ,
"4" , "5" , "6" };
myCol.AddRange(myArr1);
String[] myArr2 = new String[myCol.Count];
myCol.CopyTo(myArr2, -1);
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:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...