Range Over Built in C#

Here we use foreach to sum the numbers in a list. Arrays work like this too.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> nums = new List<int> {2, 3, 4};
        int sum = 0;
        foreach (int num in nums) {
            sum += num;
        }
        Console.WriteLine($"sum: {sum}");

        // Sometimes we actually want the indexes
        for (int i = 0; i < nums.Count; i++) {
            if (nums[i] == 3) {
                Console.WriteLine($"index: {i}");
            }
        }

        // foreach on Dictionary iterates over key/value pairs
        Dictionary<string, string> kvs = new Dictionary<string, string> {
            {"a", "apple"},
            {"b", "banana"}
        };

        foreach (var kv in kvs) {
            Console.WriteLine($"{kv.Key} -> {kv.Value}");
        }

        // foreach can also iterate over just the keys of a Dictionary
        foreach (var k in kvs.Keys) {
            Console.WriteLine($"key: {k}");
        }

        // foreach on string iterates over Unicode code points
        string str = "go";
        for (int i = 0; i < str.Length; i++) {
            Console.WriteLine($"{i} {(int)str[i]}");
        }
    }
}
$ csc Program.cs
$ Program
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Foreach in C# executes a statement or block of statements for each element in an array or a collection. Here’s the explanation of the above code:

  1. We first use the foreach loop to sum the elements in a list. The foreach loop iterates through each element in the list.
  2. When we need the index as well, we use a for loop instead.
  3. A Dictionary in C# is used to store key-value pairs. We use foreach to iterate over the key/value pairs in the dictionary.
  4. We can also iterate over just the keys of the dictionary using foreach.
  5. For strings, the for loop iterates over Unicode code points, which are represented as int in C#. The first value is the index of the character, and the second is the Unicode value of the character.

Next example: Pointers.