Lists and foreach
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- Create a List<string> called fruits
- Add three fruits with fruits.Add()
- Print each fruit with foreach
Tutor
The tutor guides you toward the answer instead of handing it over. It uses your own Claude usage.
Quick check
How do you get the number of items in a List?
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6 static void Main()
7 {
8 List<string> pets = new List<string>();
9 pets.Add("cat");
10 pets.Add("dog");
11 foreach (string p in pets)
12 {
13 Console.WriteLine(p);
14 }
15 Console.WriteLine($"Total: {pets.Count}");
16 }
17}
An empty list called pets is created.
Variables
| pets | [ ] |
Output
Step 1 of 9