Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does compiler let this slip? [duplicate]

Tags:

c#

Possible Duplicate:
Foreach can throw an InvalidCastException?

Consider the following block of code

public class Base
{
}

public class DerivedLeft : Base
{
}

public class DerivedRight : Base
{
}

class Program
{
    static void Main(string[] args)
    {
        List<Base> list = new List<Base> { new DerivedLeft(), new DerivedRight() };
        foreach (DerivedLeft dl in list)
        {
            Console.WriteLine(dl.ToString());
        }
    }
}

Notice the cast from Base to DerivedLeft in foreach statement. This compiles fine (Visual Studio 2010), without any error or even warning. Obviously, on the second loop-iteration we will get an InvalidCastException. If I was asked a question about reaction of compiler to such code, I would without a doubt say, that compiler won't let this go unnoticed and produce at least a warning. But apparently it doesn't. So, why does the compiler let this slip through?

like image 537
Trogvar Avatar asked Nov 10 '11 14:11

Trogvar


2 Answers

It's doing an implicit cast. Check out this post on the same topic for an excellent explanation by Jon Skeet:

Foreach can throw an InvalidCastException?

like image 163
JohnD Avatar answered Oct 26 '22 18:10

JohnD


Because list is of type List<Base> and the variable dl in the foreach loop is of type DerivedLeft which has Base as base class. So it can work during runtime, but it does not have to. The compiler isn't checking the initialization of your list.

like image 32
Fischermaen Avatar answered Oct 26 '22 18:10

Fischermaen