C# Lists
A List in C# is a dynamic data structure that stores multiple objects of a specified type. These objects can be accessed by their zero-based index. Unlike arrays. Lists can grow to accommodate a very large number of elements (up to about 2 billion), limited primarily by available system memory and the maximum value of an integer index.”
Syntax
Note: Before creating a list, include the
System.Collections.Genericnamespace.
There are two common ways to create a List in C#:
// Creating a List without any elements
List<T> myList = new List<T>();
Or alternatively:
// Creating a List with three elements
List<T> myList = new List<T> { element1, element2, element3 };
Parameters:
T: Represents any data type.element: Any object or variable of typeT.
Example: Creating and Accessing a List
In this example, a list is created, numbers are added, and elements are accessed by their index:
using System;using System.Collections.Generic;class Program{static void Main(){// Create a list of integersList<int> numbers = new List<int>();// Add elements to the listnumbers.Add(10);numbers.Add(20);numbers.Add(30);// Access elements by indexConsole.WriteLine(numbers[0]);Console.WriteLine(numbers[1]);Console.WriteLine(numbers[2]);}}
The output of this code is:
102030
Codebyte Example: Printing elements in a List
This example creates a new List that stores three numbers. Since each element has an index, we can print each element in the numbers list by its index:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours