Skip to main content

What are Arrays?

Sometimes we want to store a bunch of related data, however using separate variables doesn't really scale.

For example, let's take all of the Lord of the Rings characters:

string character1 = "Fodo";
string character2 = "Samwise";
string character3 = "Pippen";
string character4 = "Merry";
// ...and 50 more?

An array lets us store many values of the same type under ONE variable name:

string[] characters = {"Fodo", "Samwise", "Pippen", "Merry" };

⚠️ Arrays are fixed size, meaning once created you can't add or remove any items.

Creating an Array​

Option 1: With known values​

type[] name = { item1, item2, item3 };
  1. type[]: the type every element must be
  2. name: the variable name
  3. { }: the initial values (the array's size is the number of items)
string[] fridge = { "cheese", "yogurt", "egg" };

Option 2: With a size only​

Use this when you know how much space you need, but not what goes in them yet.

type[] name = new type[size];
  1. new: creates the array in memory
  2. size: the number of slots (fixed from now on)
string[] pantry = new string[100]; // 100 empty slots

Empty slots hold a default value:

typedefault
int0
double0.0
boolfalse
stringnull

⚠️ null means "nothing here"

Option 3: Overkill​

While valid, no one actually does this

type[] name = new type[] { item1, item2, item3 };

It just combines options 1 & 2

Reading and Writing Elements​

Use the element's index, which starts at 0 and ends at Length - 1.

name[index] // read
name[index] = value; // write

Going back to our fridge:

string[] fridge = {"cheese", "yogurt", "egg"};
# 0 1 2

Console.WriteLine(fridge[0]); // cheese

fridge[2] = "milk"; // replaces "egg"
fridge[0] = "doritos"; // replaces "cheese"
fridge[1] = "udon"; // replaces "yogurt"

assets

Length​

Use the Length property to find how many elements an array holds:

arrayName.Length

For example, to count what's in our fridge:

Console.WriteLine(fridge.Length); // ✅ 3
Console.WriteLine(fridge[fridge.Length]); // ❌ Error: IndexOutOfRangeException
Console.WriteLine(fridge[fridge.Length]); // ✅ milk

Indexes start at 0, so the last valid index is always Length - 1. Using Length itself goes one past the end.