Open In App

C# | Gets or Sets the element at the specified index in the List

List<T>.Item[Int32] Property is used to gets or sets the element at the specified index.

Properties of List:



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:




// C# program to illustrate the
// List.Item[32] property
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a List of Strings
        List<String> firstlist = new List<String>();
  
        // adding elements in firstlist
        firstlist.Add("A");
        firstlist.Add("B");
        firstlist.Add("C");
        firstlist.Add("D");
        firstlist.Add("E");
        firstlist.Add("F");
  
        // getting the element of
        // firstlist using Item property
        Console.WriteLine("Element at index 2: " + firstlist[2]);
    }
}

Output:

Element at index 2: C

Example 2:




// C# program to illustrate the
// List.Item[32] property
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a List of String
        List<String> firstlist = new List<String>();
  
        // adding elements in firstlist
        firstlist.Add("A");
        firstlist.Add("B");
        firstlist.Add("C");
        firstlist.Add("D");
        firstlist.Add("E");
        firstlist.Add("F");
  
        // Before setting the another
        // value of index 2 we will get
        // the element of firstlist
        // using Item property
        Console.WriteLine("Element at index 2: " + firstlist[2]);
  
        // setting the value of Element
        firstlist[2] = "Z";
  
        // displaying the updated value
        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:


Article Tags :
C#