Accessing and Modifying C# List Elements using the Indexer

Learn how to efficiently get and set elements in a C# `List` using the indexer. This tutorial demonstrates using square brackets (`[]`) to access elements by their index (position), providing concise and clear methods for retrieving and modifying list elements.



Getting and Setting Elements in a C# List using the Indexer

Introduction

The `List` class in C# is a dynamic array—it can grow or shrink as needed. A common operation is accessing and modifying elements using their index (position) within the list. This article shows how to get and set elements using the List's indexer.

Getting an Element

You retrieve an element using the indexer (square brackets `[]`) with the desired index (position). The first element is at index 0.

Syntax

Getting an Element Syntax

T element = myList[index];

Example

Getting an Element Example

using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
        int elementAtIndex2 = numbers[2];
        Console.WriteLine($"Element at index 2: {elementAtIndex2}"); // Output: Element at index 2: 30
    }
}

Setting an Element

To change an element's value, use the indexer followed by an assignment.

Syntax

Setting an Element Syntax

myList[index] = newValue;

Example

Setting an Element Example

using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry", "Date", "Fig" };
        Console.WriteLine("Original list:");
        foreach (var fruit in fruits) Console.WriteLine(fruit);

        fruits[2] = "Grapes"; // Modifying the element at index 2

        Console.WriteLine("\nModified list:");
        foreach (var fruit in fruits) Console.WriteLine(fruit);
    }
}
Example Output

Original list:
Apple
Banana
Cherry
Date
Fig

Modified list:
Apple
Banana
Grapes
Date
Fig
        

Conclusion

The `List` class's indexer provides a straightforward way to access and modify elements by their index. This makes it easy to work with lists and perform dynamic updates to your data.