C# | Gets or sets the element at the specified index in StringCollection
Last Updated :
01 Feb, 2019
StringCollection.Item[Int32] Property is used to get or set the element at the specified index.
Syntax:
public string this[int index] { get; set; }
Here, index is the zero-based index of the entry to get or set.
Return Value: It returns the element of String type at the specified index.
Exception: This property throws ArgumentOutOfRangeException
if the index is less than zero or index is equal to or greater than Count.
Below programs illustrate the use of above-discussed property:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
myCol.Add( "A" );
myCol.Add( "B" );
myCol.Add( "C" );
myCol.Add( "D" );
myCol.Add( "E" );
foreach (Object obj in myCol)
{
Console.WriteLine(obj);
}
Console.WriteLine( "\nAfter Item[int32] Property: \n" );
myCol[2] = "Z" ;
foreach (Object obj1 in myCol)
{
Console.WriteLine(obj1);
}
}
}
|
Output:
A
B
C
D
E
After Item[int32] Property:
A
B
Z
D
E
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
myCol.Add( "Geeks" );
myCol.Add( "GFG" );
myCol.Add( "DS" );
myCol.Add( "Class" );
myCol.Add( "Noida" );
foreach (Object obj in myCol)
{
Console.WriteLine(obj);
}
Console.WriteLine( "\nAfter Item[int32] Property: \n" );
myCol[8] = "C#" ;
foreach (Object obj1 in myCol)
{
Console.WriteLine(obj1);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...