c# · level 1 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An keeps many values together in one box.
An array is like an egg box: one box with a row of slots. Put the items between curly brackets, split by commas: string[] pets = { "cat", "dog" };. The square brackets mean many strings, not one.
Every must be the same type, so an int[] holds whole numbers only. pets.Length tells you how many items there are, with no brackets, as with a string.
Print an array on its own and C# only shows its type. To see every item, use . It glues the items into one string, with a comma and a space between each.
using System;
string[] pets = { "cat", "dog", "goldfish" };
int[] ages = { 3, 5, 1 };
Console.WriteLine(pets.Length);
Console.WriteLine(string.Join(", ", pets));
Console.WriteLine(string.Join(" and ", ages)); The first string you give string.Join is the gap it puts between the items.
guess first
Print the whole array. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
string[] pets = { "cat", "dog", "goldfish" };
Console.WriteLine(pets);
your turn
Your turn. Pack your snack box.
Type three snacks you like, one between each pair of quotes. Then press run to count them and show them all.
output
press run to see what happens
fix it
The snack list will not run. Can you fix it?
output
press run to see what happens
- C# says it expected a comma on line 3. Look between the items.
- Every item needs a comma between it and the next one. One comma is missing.
- Add a comma after "apple" on line 3, then press run.
nailed it
you packed lots of values into one box. :D
- An array holds many items of the same type.
.Lengthtells you how many items there are.string.Joinshows every item in one string.
new words in your collection
- array
- item
- string.Join
This lesson isn’t saved. A free account remembers every lesson you finish.