How to create List in C# – C# Programming Example
C# Collection List

How to create List in C#

The C# List<T> class in .NET represents a collection of strongly typed objects that can be accessed by index. In this tutorial, we learn how to use the C# List class to add, find, sort, reverse, and search items in a collection of objects using List class methods and properties.

List<T> is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List<T> class.

List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object.

The code snippet in Listing 1 creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.

Listing 1.

As you can see from Listing 1, the List<string> has an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: