Generic List

Learn about the generic counterpart of the ArrayList class.

Introduction

The ArrayList class solved the issues we had with arrays, but it also introduced new issues. .NET developers addressed the concerns with a set of generic collection classes. This lesson focuses on the List<T> class. Instead of using an object[] type array, like ArrayList does, generic collections use parameter types. In the case of List<T>, the internal array is of type T[]. Generic collections introduce strong typing. The List<int> class can only store int items, and List<string> can only store string objects. There won’t be issues like the ones we had with ArrayList.

Syntax

The List<T> class is instantiated just like any other class:

var listOfIntegers = new List<int>();

Here, we create a list that can only store integers inside. The internal array is of type int[].

Lists we create are initially empty. Empty means that the size of the internal array is zero. When we add the first item, though, a new array of size four is created.

listOfIntegers.Add(17);

Each time this array fills, it doubles in size, and values from the previous array are copied over.

This information could be useful for optimization purposes. If we’re sure that we’ll store more than a specific number of items, then we can set the initial size of the list:

var listOfIntegers = new List<int>(500);

The initial size of this list is500. The List<int> class initializes an int[] array of size 500.

Here are some of the most common operations we can perform with List<T>:

  • We can add an item to the end of the list using the Add() method.

  • We can add items from another collection to our list using the AddRange() method.

  • We can insert an item to a specific position using the Insert() method.

  • We can remove an item using the Remove() method

  • We can delete an item at a specific position using the RemoveAt() method.

Examples

Let’s explore some examples below to clarify these methods.

Add and remove items

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy