How to Create List in C#: Syntax and Examples
In C#, you create a list using the
List<T> class from System.Collections.Generic. You declare it with a type inside angle brackets, like List<int> numbers = new List<int>();, to store items of that type.Syntax
To create a list in C#, use the List<T> class where T is the type of items you want to store. You need to include using System.Collections.Generic; at the top of your file.
- List<T>: The list type that holds items of type
T. - new List<T>(): Creates a new empty list.
- T: The type of elements, like
int,string, or a custom class.
csharp
using System.Collections.Generic; List<int> numbers = new List<int>();
Example
This example shows how to create a list of strings, add items, and print them.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { List<string> fruits = new List<string>(); fruits.Add("Apple"); fruits.Add("Banana"); fruits.Add("Cherry"); foreach (string fruit in fruits) { Console.WriteLine(fruit); } } }
Output
Apple
Banana
Cherry
Common Pitfalls
Some common mistakes when creating lists in C# include:
- Forgetting to include
using System.Collections.Generic;, which causes errors becauseList<T>is not found. - Not specifying the type
Tinside the angle brackets, which is required. - Trying to add items of a different type than the list's type, causing compile errors.
csharp
/* Wrong: Missing using directive and type */ // List numbers = new List(); // Error: type required and List not found /* Correct: Specify type and include using */ using System.Collections.Generic; List<int> numbers = new List<int>(); numbers.Add(5);
Quick Reference
Here is a quick summary of how to create and use lists in C#:
| Action | Syntax Example |
|---|---|
| Create empty list | List<T> list = new List<T>(); |
| Add item | list.Add(item); |
| Access item | var item = list[index]; |
| Get count | int count = list.Count; |
| Loop through list | foreach(var item in list) { /* use item */ } |
Key Takeaways
Use
List<T> with a specified type to create a list in C#.Always include
using System.Collections.Generic; to access the List class.Add items with
Add() and access them by index or foreach loop.The list type
T must match the type of items you add.Common errors come from missing the using directive or wrong type usage.