HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C#VariablesData TypesOperatorsStringsListsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 List & Dictionary
🔀 Condition & Loop
🧩 Function
C#›Lists

Lists

Creating List<T>, adding items (Add), count (Count), and printing with string.Join.

Simple enough for a 5-year-old to understand

Create and access a list

List<T> holds ordered values. The index starts at 0. Printing the list directly outputs the type name; you print the elements using string.Join.

Example code
1
using System;
2
using System.Collections.Generic;
Required for List.
ImportRequired for List.
3
var languages = new List<string> { "C#", "Go", "Rust" };
A list with three elements.
VariableA list with three elements.
4
Console.WriteLine(languages[0]);
C# (first element)
Output / InputC# (first element)
5
Console.WriteLine(languages.Count);
3 (number of elements)
Output / Input3 (number of elements)
6
Console.WriteLine(string.Join(", ", languages));
C#, Go, Rust
Output / InputC#, Go, Rust
ImportVariableOutput / Input
💡 Hint: Number of elements .Count, first element items[0].

About this topic

List is the standard structure in C# for data of changing length. It is accessed by index like an array, but grows automatically as elements are added. You write the type inside angle brackets, and only elements of that type can enter that list.

This type safety is brought by the generic system: the compiler checks every addition and read, the wrong type causes a compilation error, and you don't need to cast the element you read.

C#'s true power when working with collections shines in LINQ: you write filtering, mapping, grouping, and sorting operations almost like a query language. Instead of writing loops, you express intent directly.

What you will learn

  • Creating a list and specifying the type
  • Accessing with Add, Remove, and index
  • Getting the number of elements with Count
  • Searching with Contains and IndexOf
  • Iterating through the list with foreach
  • Filtering and transforming with LINQ

When to use?

List is used in any dataset where the number of elements changes: database results, file lines, user choices. It appears much more often than arrays in everyday C# code.

If unique values are needed, HashSet is more appropriate; if key-value mapping is needed, Dictionary is better. Choosing the right collection improves both code and performance.

Common mistakes

Wrong

var items = new List<string> { "a", "b", "c" };
foreach (var item in items) {
    if (item == "a") items.Remove(item);
}

Deleting an element from the list you are iterating over throws "InvalidOperationException: Collection was modified". For safe deletion, you need to use RemoveAll or iterate over a copy.

Correct

var items = new List<string> { "a", "b", "c" };
items.RemoveAll(item => item == "a");

Wrong

var nums = new List<int>();
Console.WriteLine(nums[0]);

Reading an element from an empty list throws "ArgumentOutOfRangeException". You need to check Count before accessing or use LINQ's FirstOrDefault method.

Correct

var nums = new List<int>();
Console.WriteLine(nums.FirstOrDefault());

Wrong

var a = new List<int> { 1, 2, 3 };
var b = a;
b.Add(4);
Console.WriteLine(a.Count);

List is a reference type; assignment does not copy it, it gives the same list a second name. The element you add to b also appears in a, and the output becomes 4. For a copy, you need to create a new list and pass the contents.

Correct

var a = new List<int> { 1, 2, 3 };
var b = new List<int>(a);
b.Add(4);
Console.WriteLine(a.Count);

Frequently asked questions

Should I use an array or a List?

List if the number of elements will change; an array if it is fixed and performance is very critical. List already uses an array in the background and enlarges it when full. In everyday application code, List is almost always the right choice.

What is LINQ and why is it used?

It is a set of methods that allows you to filter, transform, sort, and group collections. Instead of writing loops, you express what you want in a single chain; the code becomes both shorter and clearly shows the intent.

How do I sort a list?

The Sort method sorts the list IN-PLACE. LINQ's OrderBy method returns a new sorted sequence and does not touch the original list; it also lets you specify which field to sort by in a single line. The second way is more common in modern C# code.

Summary

List is C#'s standard structure for data of changing length and provides generic type safety. Since it is a reference type, assignment does not copy it, deleting while iterating throws an error, and LINQ expresses collection operations without loops.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code