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.
CodePudding user response:
A foreach
loop has a builtin explicit cast to the target type.
That's why you can write:
object[] things = ...
foreach(string s in things)
{
// ...
}
You can see this in the C# language spec, 8.8.4.:
8.8.4 The foreach statement
foreach (V v in x) embedded-statement
is then expanded to:
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
So it works in the same way as if you'd write:
double d = 123.45;
int i = (int) d;
CodePudding user response:
checking you code,
//here you need a cast
double x = 1.23;
int y = (int)x; //explicit cast
But in the loop
int x = 0;
ReadOnlyCollection<double> y = new ReadOnlyCollection<double>(new double[3] {1.23, 2.34, 3.45 });
// the z variable is to get the int in the y list, like a hidden cast
foreach (int z in y)
{
x = z;
}
Best Regards