Home » C# » How to initialize a C# list, with code examples

How to initialize a C# list, with code examples

If you are coding in C# then you can be pretty certain at some point you’ll need to use a C# List. This post will teach you how to initialize a C# list.

How to initialise a C# List

A C# List is a collection of strongly typed objects, and in order to use it you must import the correct namespace as follows:

using System.Collections.Generic

There’s a few ways to initialize a List and I’ll show examples of each. Which one you use will depend on the size of the List you are initialising, the data that will fill the List, and whether you have your data when you initialise it or not.

If you don’t have any of the data yet then your initialiser will be like one of these examples:

//List of object type Drink - see Drink model definition below
List<drink> = new List<Drink>;

//list of integers
List<int> = new List<int>;

//list of strings
List<string> = new List<string>;

This next example shows a simple C# collection intialiser, building a collection of integers:

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Equally you could create a List of strings:

List<string> countries = new List<string> { France, USA, Germany, England};

Or you can initialize a list of objects using object initializers:

List<Drink> drinks = new List<Drink> { 
  new Drink{ Name = "Beer", Id=8 }, 
  new Drink{ Name = "Champagne", Id=312 }, 
  new Drink{ Name = "Lemonade", Id=14 } };

This example, and subsequent examples make use of typed Lists using the Drink object as defined here:

internal class Drink
{
   public string Name { get; set; }
   public int Id { get; set; }
}

You may also be interested in: