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

How to initialize a C# list, with code examples

By Emily

If you are coding in C# then you can be pretty certain at some point you’ll need to create a C# List with values of some kind. Maybe a list of strings, a list of integers, or a list of custom objects. This post will teach you how to initialize a C# list with values and initialize a list of objects. I’ll provide C# list initialization examples of integers, strings, and objects.

How to initialize 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 are 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 initializing, the data that will fill the List, and whether you have your data already when you initialize it or not.

Initialize an empty list

If you don’t have any of the data yet then your initializer 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>;

C# list initialization of integer collection

This next example shows a simple C# collection intializer, which initializes a list of values, in this case, 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 C# List of strings, or initialize a List with string values:

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

Create a C# list using object initializers

This C# list initialization example shows how you can initialize a list of objects :

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; }
}

Summary

You now know how to perform a C# list initialization of objects, integers, and strings. I’ve shown you how to initialize a new empty list, and how to initialize a list of values. Now you’ve got this far, you’ll probably want to know how to add new items to the list, remove items from the list, and also how to sort the List of values.

You may also be interested in: