C#: looping over int for IEnumerable<double> causes no casting error
Asked Answered
D

2

5

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.

Dissuade answered 18/11, 2022 at 13:9 Comment(1)
You are already casting by explicitly writing int, use var and see the result.Disentangle
H
9

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;
Humperdinck answered 18/11, 2022 at 13:13 Comment(2)
Thanks! Just for reference adding these: github.com/dotnet/roslyn/discussions/57308 github.com/dotnet/docs/issues/4505Dissuade
Was curious how it decompiles and did this: sharplab.io/… - no idea why it does the whole shenanigans with array2 array3Presber
S
-1

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

Sextans answered 18/11, 2022 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.