I have the following short C# program:
IList<string> listString = new List<String>();
IList<object> listObject;
listObject = listString;
This program doesn't compile. The last line causes the following compilation error:
Cannot implicitly convert type 'System.Collections.Generic.IList' to 'System.Collections.Generic.IList'.
An explicit conversion exists (are you missing a cast?)
So, I've added the cast:
listObject = (IList<object>)listString;
Now the program compiles properly, but fails at runtime. An InvalidCastException
is raised with the following message:
Unable to cast object of type 'System.Collections.Generic.List'1[System.String]' to type 'System.Collections.Generic.IList'1[System.Object]'.
Either the cast is illegal and should be caught by the compiler, or it is legal and shouldn't throw an exception at runtime. Why the inconsistent behavior?
CLARIFICATION: I am not asking why the cast fails. I understand why such casting is problematic. I am asking why the cast fails only at runtime.