Collection<T>.Item[Int32] property is used to get or set the element at the specified index.
Syntax:
public T this[int index] { get; set; }
Here, index is the zero-based index of the element to get or set.
Return Value: The element at the specified index.
Exception: This method will give ArgumentOutOfRangeException if the index is less than zero or index is equal to or greater than Count.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< string > myColl = new Collection< string >();
myColl.Add( "A" );
myColl.Add( "B" );
myColl.Add( "C" );
myColl.Add( "D" );
myColl.Add( "E" );
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
Console.WriteLine( "Element at index 2 is : " + myColl[2]);
Console.WriteLine( "Element at index 3 is : " + myColl[3]);
myColl[3] = "GFG" ;
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
}
}
|
Output:
A
B
C
D
E
Element at index 2 is : C
Element at index 3 is : D
A
B
C
GFG
E
Example 2:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< int > myColl = new Collection< int >();
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
Console.WriteLine( "Element at index -1 is : " + myColl[-1]);
myColl[2] = 10;
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
}
}
|
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
Note:
- Collection<T> accepts null as a valid value for reference types and allows duplicate elements.
- This property provides the ability to access a specific element in the collection by using the syntax : myCollection[index].
- Retrieving the value of this property is an O(1) operation.
- Setting the property is also an O(1) operation.
Reference: