Open In App

C# | Copy the elements of a string array to the end of the StringCollection

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.AddRange(String[]) method is used to copy the elements of a string array to the end of the StringCollection.



Syntax:

public void AddRange (string[] value);

Here, string[] value is an array of strings which will be added to the end of the StringCollection. The array itself can not be null but it can contain elements that are null.



Exception: This method will give ArgumentNullException if value is null.

Note:

Below programs illustrate the use of StringCollection.AddRange(String[]) Method:

Example 1:




// C# code to copy the elements
// of a string array to the end
// of the StringCollection
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 myArr
        String[] myArr = new String[] { "A", "B", "C", "D", "E" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // Displaying elements in StringCollection
        foreach(Object obj in myCol)
        {
            Console.WriteLine("{0}", obj);
        }
    }
}

Output:
A
B
C
D
E

Example 2:




// C# code to copy the elements
// of a string array to the end
// of the StringCollection
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 myArr
        String[] myArr = new String[] { "2", "3", "4", "5", "6" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // Displaying elements in StringCollection
        foreach(Object obj in myCol)
        {
            Console.WriteLine("{0}", obj);
        }
    }
}

Output:
2
3
4
5
6

Reference:


Article Tags :
C#