The compiler fails to detect that line 3 will error:
IList<IList<double>> xs = new List<IList<double>> { new List<double> { 2 } };
IList<string> x0 = xs.First(); // does not compile, as expected
foreach (IList<string> x in xs) { } // works, unexpectedly!
(Even though there’s no error, Visual Studio does suggest on line 3 that there is an implicit cast, which may fail at runtime.)
Interestingly, the compiler successfully detects the issue here:
IList<double> xs = new List<double> { 2 };
string x0 = xs.First(); // does not compile, as expected
foreach (string x in xs) { } // also does not compile, as expected
Is there a good reason why line 3 just gives a suggestion and not an error, like in lines 2, 5, and 6?
>Solution :
foreach is just :
try {
while (enumerator.MoveNext()) {
IList<string> x = (IList<string>)enumerator.Current;
}
}
The question boils down to – should this be a compile-time error:
IList<string> x = (IList<string>)enumerator.Current;
According to the 10.3.5 Explicit reference conversions section from the language specification regarding allowed explicit conversions:
From any interface_type S to any interface_type T, provided S is not
derived from T.
So, the answer is no.