Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:




// 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:



Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads