Chapter 7: Arrays and Collections (Basics)
1. What is an Array? (Super Simple Analogy)
Think of an array like a row of numbered boxes in a shelf:
- All boxes are the same type (all hold integers, or all hold strings, etc.)
- Each box has a number (called index) starting from 0
- You can put something in each box and get it back later by its number
2. Single-Dimensional Arrays (The Most Common)
Syntax to declare and initialize:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Declare an array (size must be known) int[] numbers = new int[5]; // Creates 5 boxes, all 0 by default // Declare and immediately fill string[] days = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; // Modern short way (C# 12+ style) string[] fruits = ["Apple", "Banana", "Mango", "Orange"]; // Access elements (index starts at 0!) Console.WriteLine(fruits[0]); // "Apple" Console.WriteLine(fruits[2]); // "Mango" // Change an element fruits[1] = "Pineapple"; Console.WriteLine(fruits[1]); // "Pineapple" // Length property (very useful!) Console.WriteLine($"We have {fruits.Length} fruits"); |
Real example – Store and print student scores:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
int[] scores = new int[5]; Console.WriteLine("Enter 5 student scores:"); for (int i = 0; i < scores.Length; i++) { Console.Write($"Score {i + 1}: "); scores[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("\nScores entered:"); foreach (int score in scores) { Console.WriteLine(score); } |
3. Multi-Dimensional Arrays (Like a Table / Grid)
Rectangular 2D array – all rows have the same length
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 3 rows × 4 columns int[,] matrix = new int[3, 4]; // Or initialize directly int[,] ticTacToe = new int[,] { { 1, 0, 2 }, { 0, 1, 0 }, { 2, 0, 1 } }; // Access: [row, column] Console.WriteLine(ticTacToe[0, 0]); // 1 (top-left) Console.WriteLine(ticTacToe[2, 2]); // 1 (bottom-right) // Print whole board for (int row = 0; row < ticTacToe.GetLength(0); row++) // rows { for (int col = 0; col < ticTacToe.GetLength(1); col++) // columns { Console.Write(ticTacToe[row, col] + " "); } Console.WriteLine(); } |
4. Jagged Arrays (Array of Arrays – Rows Can Have Different Lengths)
Very useful when rows have different sizes.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Jagged array: array of arrays int[][] jagged = new int[3][]; // Initialize each row separately jagged[0] = new int[] { 1, 2, 3 }; jagged[1] = new int[] { 4, 5 }; jagged[2] = new int[] { 6, 7, 8, 9, 10 }; // Access Console.WriteLine(jagged[1][0]); // 4 Console.WriteLine(jagged[2][4]); // 10 // Print with foreach for (int i = 0; i < jagged.Length; i++) { Console.Write($"Row {i + 1}: "); foreach (int num in jagged[i]) { Console.Write(num + " "); } Console.WriteLine(); } |
5. Introduction to Generic Collections (Much Better Than Arrays!)
Arrays are fixed size and not very flexible. Modern C# uses generic collections from System.Collections.Generic – they can grow, shrink, and are much easier to use.
You must add this line at the top of your file:
|
0 1 2 3 4 5 6 |
using System.Collections.Generic; |
A. List<T> – The Most Common Collection (Like a Dynamic Array)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// Create a list List<string> names = new List<string>(); // Add items names.Add("Rahul"); names.Add("Priya"); names.Add("Amit"); // Insert at position names.Insert(1, "Sneha"); // Remove names.Remove("Amit"); // Access like array Console.WriteLine(names[0]); // "Rahul" // Count instead of Length Console.WriteLine($"We have {names.Count} friends"); // Modern way to create and fill var fruits = new List<string> { "Apple", "Banana", "Mango" }; // Loop foreach (string fruit in fruits) { Console.WriteLine(fruit); } |
B. Dictionary<TKey, TValue> – Key-Value Pairs (Like a Phone Book)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Create dictionary Dictionary<string, int> phoneBook = new Dictionary<string, int>(); // Add entries phoneBook["Rahul"] = 9876543210; phoneBook["Priya"] = 9123456789; phoneBook["Amit"] = 9988776655; // Access by key Console.WriteLine($"Rahul's number: {phoneBook["Rahul"]}"); // Check if exists if (phoneBook.ContainsKey("Sneha")) { Console.WriteLine(phoneBook["Sneha"]); } else { Console.WriteLine("Sneha not in phone book"); } // Loop through all foreach (var pair in phoneBook) { Console.WriteLine($"{pair.Key}: {pair.Value}"); } |
Mini-Project: Student Grade Manager
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System.Collections.Generic; Console.WriteLine("=== Student Grade Manager ===\n"); var students = new List<string> { "Rahul", "Priya", "Amit", "Sneha" }; var grades = new Dictionary<string, double>(); // Input grades foreach (string student in students) { Console.Write($"Enter grade for {student}: "); double grade = double.Parse(Console.ReadLine()); grades[student] = grade; } // Show report Console.WriteLine("\n=== Grade Report ==="); double total = 0; foreach (var pair in grades) { Console.WriteLine($"{pair.Key,-10}: {pair.Value:F1}%"); total += pair.Value; } double average = total / grades.Count; Console.WriteLine($"\nAverage grade: {average:F1}%"); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); |
Quick Comparison Table
| Feature | Array | List<T> | Dictionary<TKey,TValue> |
|---|---|---|---|
| Size | Fixed | Dynamic (grow/shrink) | Dynamic |
| Access by | Index (0,1,2…) | Index | Key |
| Ordered? | Yes | Yes | No (but can use OrderedDict) |
| Duplicate keys/values? | Allowed | Allowed | Keys must be unique |
| Most common use | Fixed data, performance | Most lists of items | Lookup by name/ID |
Your Homework (Super Fun & Practical!)
- Create a new console project called CollectionPlayground
- Make a Shopping List Manager:
- Use a List<string> for items
- Let user add 5 items (loop + Add)
- Let user remove one item by name
- Print the final list with numbers (1. Milk, 2. Bread…)
- Bonus: Create a Dictionary<string, decimal> for item → price
- Calculate total cost of shopping
Next lesson: User Input and Output in Depth + Exception Handling Basics – we’re going to make programs that are safe and user-friendly!
You’re doing absolutely amazing! 🎉 Any part confusing? Want more examples with arrays or collections? Just tell me — I’m right here for you! 💙
