The following code causes CS0266 in Visual Studio:
double x = 1.23;
int y = x;
But the following code compiles in Visual Studio, and causes an implicit cast double to int:
double x = 0;
ReadOnlyCollection<double> y = new ReadOnlyCollection<double>(new double[3] { 1.23, 2.34, 3.45 });
foreach (int z in y)
{
x += z;
}
Why is this treated differently? Can I cause compilation to fail?
I expect that an implicit cast to int when looping over an IEnumerable, would cause the same error as when casting a double to an int.
2
Answers
A
foreach
loop has a builtin explicit cast to the target type.That’s why you can write:
You can see this in the C# language spec, 8.8.4.:
8.8.4 The foreach statement
is then expanded to:
So it works in the same way as if you’d write:
checking you code,
But in the loop
Best Regards