Sobes.tech
Junior

What objects can be used in a foreach loop?

sobes.tech AI

Answer from AI

In a foreach loop, objects implementing the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interfaces can be used.

Main object types:

  • Arrays (single- and multi-dimensional)
  • Collections implementing IEnumerable or IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> and Stack<T>
    • Other classes from the System.Collections and System.Collections.Generic namespaces
  • Strings (System.String - iterated over characters)
  • Objects returned by LINQ queries
  • Custom data types implementing one of the aforementioned interfaces.

Example:

// Array
string[] colors = {"red", "green", "blue"};
foreach (string color in colors)
{
    // ...
}

// List<T>
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
    // ...
}

// string
string text = "hello";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> iterates over KeyValuePair<TKey, TValue>
Dictionary<string, int> ages = new Dictionary<string, int>
{
    {"Alice", 30},
    {"Bob", 25}
};
foreach (KeyValuePair<string, int> entry in ages)
{
    // entry.Key, entry.Value
}

// Custom class implementing IEnumerable<T>
public class MyCollection : IEnumerable<int>
{
    private int[] _data = {10, 20, 30};

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var item in _data)
        {
            yield return item; // Using iterator
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

// Using custom class
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}