C# Data Structures
Data Structures
A data structure is a way to store and organize many values, so they are easy to use.
You already know one data structure: the array. An array stores many values in one variable.
But an array has a fixed size. If you create an array with 3 items, it always has 3 items. You cannot add a fourth item later, and you cannot remove an item.
Often, you don't know how many values you will have. Think of a shopping list: it grows when you add items, and it gets shorter when you buy them.
Arrays are still a good choice when the number of values never changes, like the 7 days of a week.
Collections
C# has ready-made data structures that can grow and shrink. They are called collections.
The collections are in the System.Collections.Generic namespace. To use them, add this line at the top of your file, below using System;:
Example
// Include the namespace that holds the collections
using System.Collections.Generic;
These are the most common collections:
| Collection | What it stores | Use it when |
|---|---|---|
| List | Values in order, like an array that can grow | You want to add and remove values, and get them by index |
| Dictionary | Pairs of keys and values | You want to find a value by a key, like a phone number by a name |
| HashSet | Values, each value only once | You don't want the same value two times |
| Stack | Values in a pile: the last value in is the first value out | You want the newest value first, like the Undo button |
| Queue | Values in a line: the first value in is the first value out | You want the oldest value first, like a line at a shop |
A First Example
Here is a small example with a List. It starts empty, and you can add as many cars as you want:
Example
List<string> cars = new List<string>();
cars.Add("Volvo");
cars.Add("BMW");
cars.Add("Ford");
Console.WriteLine(cars.Count); // 3
cars.Add("Mazda");
Console.WriteLine(cars.Count); // 4
Example explained
List<string>is a list that stores strings. The type inside< >tells C# what kind of values the list holds.Add()adds a value to the end of the list.Counttells you how many values the list has. It changes from 3 to 4 when you add Mazda.
You will learn all about lists in the next chapter, and then about the other collections.