C# | Gets or Sets the element at the specified index in the List
Last Updated :
01 Feb, 2019
List<T>.Item[Int32] Property is used to gets or sets the element at the specified index.
Properties of List:
- It is different from the arrays. A list can be resized dynamically but arrays cannot.
- List class can accept null as a valid value for reference types and it also allows duplicate elements.
- If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public T this[int index] { get; set; }
Parameter:
index: It is the zero-based index of the element to get or set of type System.Int32.
Return Value: This property returns the element at the specified index.
Exception: This method will give ArgumentOutOfRangeException if the index is less than 0 or index is equal to or greater than Count.
Below are the examples to illustrate the use of List<T>.Item[Int32] Property:
Example 1:
using System;
using System.Collections.Generic;
class Geeks {
public static void Main(String[] args)
{
List<String> firstlist = new List<String>();
firstlist.Add( "A" );
firstlist.Add( "B" );
firstlist.Add( "C" );
firstlist.Add( "D" );
firstlist.Add( "E" );
firstlist.Add( "F" );
Console.WriteLine( "Element at index 2: " + firstlist[2]);
}
}
|
Output:
Element at index 2: C
Example 2:
using System;
using System.Collections.Generic;
class Geeks {
public static void Main(String[] args)
{
List<String> firstlist = new List<String>();
firstlist.Add( "A" );
firstlist.Add( "B" );
firstlist.Add( "C" );
firstlist.Add( "D" );
firstlist.Add( "E" );
firstlist.Add( "F" );
Console.WriteLine( "Element at index 2: " + firstlist[2]);
firstlist[2] = "Z" ;
Console.WriteLine( "After Setting the new value at 2: " + firstlist[2]);
}
}
|
Output:
Element at index 2: C
After Setting the new value at 2: Z
Reference:
Share your thoughts in the comments
Please Login to comment...