Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# compiler fails to error when it should

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading