foreach patterns; collection initializers
Write safe foreach loops over arrays, lists, and dictionaries; initialize collections concisely with collection initializer syntax.
foreach patterns; collection initializers is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Overview
Goal: Iterate safely with foreach and create/populate collections with collection initializers.
- foreach over arrays/lists
- foreach over dictionaries
- List<T> and Dictionary<K,V> initializers
foreach arrays & lists
foreach is simple and safe: it reads items one by one without manual indexing.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
int[] nums = new int[] { 2, 4, 6 };
int sum = 0;
foreach (int n in nums) // no index to manage, safe bounds
{
sum = sum + n;
}
Console.WriteLine("Sum = " + sum);
List<string> names = new List<string>();
names.Add("Ada");
names.Add("Alan");
foreach (string s in names)
{
Console.WriteLine("Hi " + s);
}
}
}
Index with foreach
If you need an index with foreach, keep a small counter variable.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
List<string> items = new List<string>();
items.Add("apple");
items.Add("banana");
items.Add("cherry");
int i = 0;
foreach (string item in items)
{
Console.WriteLine("#" + i + ": " + item);
i = i + 1; // manual index when needed
}
}
}
foreach dictionary
Dictionary iteration yields KeyValuePair<K,V>; or iterate Keys/Values only.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
Dictionary<string, int> stock = new Dictionary<string, int>();
stock["pen"] = 10;
stock["book"] = 5;
foreach (KeyValuePair<string, int> kv in stock)
{
Console.WriteLine(kv.Key + " -> " + kv.Value);
}
// Iterate keys or values only
foreach (string k in stock.Keys) { Console.WriteLine("Key: " + k); }
foreach (int v in stock.Values) { Console.WriteLine("Value: " + v); }
}
}
List<T> initializer
Collection initializer creates and fills a list in one expression; it expands to repeated Add calls.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
// Calls Add for each element under the hood
List<string> fruits = new List<string> { "apple", "banana", "cherry" };
foreach (string f in fruits)
{
Console.WriteLine(f);
}
}
}
Dictionary initializer
Dictionary initializer uses { key, value } entries; this expands to Add(key, value) calls.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
// Each { key, value } becomes Add(key, value)
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Ada", 95 },
{ "Alan", 90 }
};
// Show contents
foreach (KeyValuePair<string, int> kv in scores)
{
Console.WriteLine(kv.Key + " = " + kv.Value);
}
}
}
Initializer benefit
Recap
Recap: Use foreach to iterate arrays, lists, and dictionaries safely. Prefer collection initializers to create and fill collections concisely.
Frequently asked questions
Is the “foreach patterns; collection initializers” lesson free?
Yes — the full text of “foreach patterns; collection initializers” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “foreach patterns; collection initializers”?
Write safe foreach loops over arrays, lists, and dictionaries; initialize collections concisely with collection initializer syntax. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “foreach patterns; collection initializers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Arrays, slicing, List , Dictionary
- foreach patterns; collection initializers
- LINQ preview: Where, Select, OrderBy, Take/Skip; deferred execution