34
In C#, I cannot implicitly convert a long to an int.
long l = 5;
int i = l; // CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
This produces said error. And rightly so; if I do that, I am at risk of breaking my data, due to erroneous truncation. If I decide that I know what I am doing, then I can always do an explicit cast, and tell the compiler that it's okay to truncate, I know best.
int i = (int)l; // OK
However, the same mechanism does not seem to apply when using a foreach loop.
IList<long> myList = new List<long>();
foreach (int i in myList)
{
}
The compiler does not even generate a warning here, even though it is essentially the same thing: an unchecked truncation of a long to an int, which might very well break my data.
So my question is simply: Why does this foreach not create the same error as the variable assignment does?