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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With