C# Array and List

Last modified: July 11, 2021

An array is used to store multiple values on a single variable. For example, as below, there are many cars, instead of creating car1, car2, car3 to hold three different cars, we used an array variable to hold them all.

static void Main(string[] args) { string car1 = "Tesla X"; string car2 = "Tesla S"; string car3 = "BMW i3"; string[] car = { "Tesla X", "Tesla S", "BMW i3" }; }

To access a value from an array, we used `array[index]'. Index starts from zero.

var aCar = car[1]; //i.e. "Tesla S"

Both Array and List store similar types in the collection, however, there are some differences between them. The list is a dynamic data structure, meaning we do not need to define how many items when we declare it.

Unline Array, we have special methods for List, adding, removing searching, and sorting.

We instantiate list as below.

List<string> carlist = new List<string>() { "Tesla X", "Tesla S", "BMW i3" };
Add() Method
carlist.Add("Tesla 3"); carlist.Add("Tesla Y");
Remove() Method
carlist.Remove("Tesla 3");