Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

23 Nov 2006

A better look at the Foreach statement

Earlier this week i was a bit surprised that the following code compiled without errors or warning messages. I expected at least a warning that i was trying to assign a double value to an integer parameter

static void Main(string[] args)
{
	double[] values = new double[] { 1.1, 2.2, 3.3, 4.4, 5.5 };

	Console.WriteLine("foreach with int:");

	// happily iterate over the double values as if they are ints...
	// this outputs the lines 1, 2, 3, 4 and 5.
	foreach (int value in values)
	{
		Console.WriteLine(value);
	}
}

So i decided to dive into the C# Language Specification (Section 15.8.4 The foreach statement) where i found the following:

A foreach statement of the form foreach (V v in x) embedded-statement is then expanded to:
```csharp


{
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
}

> </div>