Learn C# · lesson 26 of 61 · about 7 minutes
Arrays
Meet the next wave: store a fixed number of enemies in an array, then read them by index.
What you'll learn
- Create arrays with values or a size
- Read and change items by index
- Use Length and ^1
The next wave
After the shop, the arena gates open on a new wave: a Bat, a Goblin and a Troll. Three separate variables would work, but the battle needs to say how many enemies there are and let the hero pick one by number. A string[] called enemies holds all three in order, and it always knows its own Length.
A row of boxes
int[] scores = { 7, 9, 4 };makes an array with valuesnew int[5]makes five zerosscores[0]is the first item;scores.Lengthis how manyscores[^1]counts from the end: the last item- An array's size never changes after it's made
Reading outside the array throws an IndexOutOfRangeException.
Arrays
int[] scores = { 7, 9, 4 };
scores[2] = 10;
Console.WriteLine($"{scores[0]} {scores[^1]} ({scores.Length} items)");
string[] slots = new string[3];
slots[1] = "hat";
Console.WriteLine($"[{slots[0]}] [{slots[1]}]");
Console.WriteLine(string.Join(", ", scores));Output
7 10 (3 items)
[] [hat]
7, 9, 10Tip
Unset items are 0 for numbers, false for bool and null for strings. Printing a null string inside $"..." shows nothing.
Tip
A typed number has to be checked before it becomes an index. People count from 1, so the item for number n is at index n - 1.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.