C# | Get or Set at specified index in 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.

Properties:

  • StringCollection accepts null as a valid value and allows duplicate elements.
  • String comparisons are case-sensitive.
  • Elements in this collection can be accessed using an integer index.
  • Indexes in this collection are zero-based.

Below programs illustrate how to get or set the elements at the specified index in StringCollection:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get or set the element at the
// specified index in 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[] { "G", "e", "E", "k", "s" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // To get element at index 2
        Console.WriteLine(myCol[2]);
    }
}

chevron_right


Output:

E

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get or set the element at the
// specified index in 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[] { "3", "5", "7", "11", "13" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // To get element at index 3
        Console.WriteLine(myCol[3]);
  
        // Set the value at index 3 to "8"
        myCol[3] = "8";
  
        // To get element at index 3
        Console.WriteLine(myCol[3]);
    }
}

chevron_right


Output:

11
8


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.