DEV Community

Sabin Sim
Sabin Sim

Posted on

36. C#(Lists in C#)

Full Runnable Code

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 1) Create list
        List<string> words = new List<string>();

        Console.WriteLine("Initial Count: " + words.Count); // 0
        Console.WriteLine();

        // 2) Add
        words.Add("one");
        words.Add("two");

        Console.WriteLine("Count after Add: " + words.Count);
        Console.WriteLine();

        // 3) Print with foreach
        Console.WriteLine("Current list:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
        Console.WriteLine();

        // 4) Remove by value
        words.Remove("one");

        Console.WriteLine("After Remove:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
        Console.WriteLine();

        // 5) AddRange
        words.AddRange(new string[] { "three", "four", "five" });

        Console.WriteLine("After AddRange:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
        Console.WriteLine();

        // 6) IndexOf
        Console.WriteLine("IndexOf(\"four\"): " + words.IndexOf("four"));
        Console.WriteLine("IndexOf(\"seven\"): " + words.IndexOf("seven"));
        Console.WriteLine();

        // 7) Contains
        Console.WriteLine("Contains(\"five\"): " + words.Contains("five"));
        Console.WriteLine("Contains(\"seven\"): " + words.Contains("seven"));
        Console.WriteLine();

        // 8) RemoveAt
        words.RemoveAt(0);

        Console.WriteLine("After RemoveAt(0):");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
        Console.WriteLine();

        // 9) Clear
        words.Clear();
        Console.WriteLine("Count after Clear: " + words.Count);

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

0. The Real Goal of This Lesson

A List<T> is a collection that can grow and shrink while keeping index-based access.

If this is not clear:

  • arrays and lists feel interchangeable
  • Add, Remove, and Count feel like random methods
  • dynamic collections become harder to reason about

This lesson is about understanding why List<T> exists and how it behaves structurally.


1. Why Do We Need List?

The biggest limitation of arrays is this:

Arrays have fixed size.

Example:

int[] numbers = new int[3];
Enter fullscreen mode Exit fullscreen mode

Those 3 slots stay 3 slots.

But real programs often deal with changing amounts of data:

  • a shopping cart may contain 2 items
  • or 100 items
  • or become empty again

That is why List<T> exists.

It gives you:

variable-sized storage with index-based access


2. The Basic Concept of List

List<string> words = new List<string>();
Enter fullscreen mode Exit fullscreen mode

Structure:

  • List<T> is a class → it needs new
  • <string> defines the element type
  • all elements must be of the same type

So this is:

a dynamic collection of strings

Unlike arrays, the number of elements is not fixed at creation.


3. Length vs Count

Arrays use:

numbers.Length
Enter fullscreen mode Exit fullscreen mode

Lists use:

words.Count
Enter fullscreen mode Exit fullscreen mode

Different names.

Same core meaning:

current number of elements

This distinction matters because many beginners try to write:

words.Length
Enter fullscreen mode Exit fullscreen mode

That does not work for List<T>.


4. The Most Important List Methods

Add

words.Add("one");
Enter fullscreen mode Exit fullscreen mode

Adds one element to the end of the list.


Remove

words.Remove("one");
Enter fullscreen mode Exit fullscreen mode

Removes by value.

Behavior:

  • if the value exists → it is removed
  • if the value does not exist → nothing happens

RemoveAt

words.RemoveAt(0);
Enter fullscreen mode Exit fullscreen mode

Removes by index.

Important:

invalid index = runtime error

So index rules still matter.


AddRange

words.AddRange(new string[] { "three", "four" });
Enter fullscreen mode Exit fullscreen mode

Adds multiple elements at once.

This is useful when you already have a collection to append.


IndexOf

words.IndexOf("four");
Enter fullscreen mode Exit fullscreen mode

Behavior:

  • returns the index if found
  • returns -1 if not found

This is a search result, not a boolean.


Contains

words.Contains("five");
Enter fullscreen mode Exit fullscreen mode

Returns:

true or false
Enter fullscreen mode Exit fullscreen mode

This is a direct membership check.


Clear

words.Clear();
Enter fullscreen mode Exit fullscreen mode

Removes all elements from the list.

After this:

words.Count == 0
Enter fullscreen mode Exit fullscreen mode

5. List vs Array

Array List
Fixed size Variable size
Length Count
Cannot Add Can Add
Cannot Remove directly Can Remove

The structural difference is simple:

  • array = fixed container
  • list = resizable container

6. Index Rules Are Still the Same

A list is dynamic, but indexing still starts at 0.

If the list has 2 elements, valid indices are:

0, 1
Enter fullscreen mode Exit fullscreen mode

So this:

words.RemoveAt(2);
Enter fullscreen mode Exit fullscreen mode

causes a runtime error.

Dynamic size does not remove index boundaries.


7. Structural Execution Flow of Removal

This is a very important mental model.

When an element is removed from a list:

the remaining elements shift left to fill the gap

Example:

[10, 20, 30]
RemoveAt(0)
Enter fullscreen mode Exit fullscreen mode

Becomes:

[20, 30]
Enter fullscreen mode Exit fullscreen mode

Now:

  • 20 moves to index 0
  • 30 moves to index 1

This is why indices must be reinterpreted after removal.


Final Summary

Arrays have fixed size.
List<T> is a variable-sized collection with index-based access and built-in methods like Add, Remove, and Count.


Learning Check

Explain the execution flow of this code step by step:

List<int> numbers = new List<int>();

numbers.Add(10);
numbers.Add(20);
numbers.Remove(10);

Console.WriteLine(numbers.Count);
Console.WriteLine(numbers[0]);
Enter fullscreen mode Exit fullscreen mode

Answer these precisely:

  1. What remains in the list after Remove(10)?
  2. What is the value of Count?
  3. What does numbers[0] print?
  4. Why does that happen? Explain it in terms of index shifting after removal.

Top comments (0)