C# List Examples
You have questions about the List collection in the .NET Framework, which is located in the System.Collections.Generic namespace. You want to see examples of using List and also explore some of the many useful methods it provides, making it an ideal type for dynamically adding data. This document has lots of tips and resources on the List constructed type, with examples using the C# programming language.
Lists are dynamic arrays in the C# language.
They can grow as needed when you add elements.
They are considered generics and constructed types.
You need to use < and > in the List declaration.
They can grow as needed when you add elements.
They are considered generics and constructed types.
You need to use < and > in the List declaration.
Add values
To start, we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets are part of the declaration type, not conditional operators that mean less or more than. They are treated differently in the language.
Program that adds elements to List [C#]
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);