List<T>
A List is a stretchy array that grows and shrinks as you add or remove things. It is like a backpack that expands to fit more books.
In this page:
Syntax
List<type> listName = new List<type>();
listName.Add(item);
listName.Remove(item);
listName[0];
listName.Count;
List<T>
List<T> is a dynamically resizable collection from System.Collections.Generic, unlike fixed-size arrays. You can add, remove, and search elements, and it grows automatically as needed. It's the most commonly used general-purpose collection in C#.
Note:
Prefer
List<T> over arrays whenever the number of elements can change at runtime.Example: List<T>
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> { "Amy", "Bo" };
names.Add("Cy");
names.Remove("Bo");
Console.WriteLine(names.Count);
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Removing items from a list inside a
foreach, which throwsInvalidOperationException. - Using an index equal to
Count, which throwsArgumentOutOfRangeException. - Forgetting
using System.Collections.Generic;when implicit usings are disabled.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: