Codeloft
0 0 XP

Lists and foreach

8 min 20 XP + 10 for no hints

A List holds many values of one type and can grow. Add using System.Collections.Generic;, then create one: List<string> names = new List<string>();

names.Add("Asha"); adds an item, and names.Count tells you how many there are.

foreach visits every item in order: foreach (string n in names) { … }. Open Step through to watch it work.

Example (inside Main)
List<int> scores = new List<int> { 7, 9 };
scores.Add(10);
Console.WriteLine(scores.Count);
Output
3
Lists use Count; arrays use Length. Mixing them up is a common error.

Your tasks

0 of 3 done
  1. Create a List<string> called fruits
  2. Add three fruits with fruits.Add()
  3. Print each fruit with foreach

Quick check

How do you get the number of items in a List?

Program.csChecked as you type
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.