Incompatible Double Casting - Not Detected by Compiler

c#, casting

Solution

The `List<T>` class is not sealed, so the the compiler cannot be sure that the cast from `List<T>` to `IQueryable<T>` is invalid.

Suppose you define a subclass like this

class QueryableList<T> : List<T>, IQueryable<T>
{
    ...
}

Then the cast would be valid.

Problem

In testing some code this evening, I naively tried a double-cast to convert a `List` to `IQueryable` (Note: I know about `.AsQueryable()`, please read the whole question): ``` var data = (IQueryable<MyType>)(List<MyType>)Application["MyData"]; ``` I didn't think about whether or not that was valid, but I noticed that there were no errors in Visual Studio, and I was able to compile the code without errors, so I assumed it would work. But after I published the web application, and went to view the page, I got the following error (as expected): Unable to cast object of type 'System.Collections.Generic.List`1[MyType]' to type 'System.Linq.IQueryable`1[MyType]'. Even though the type of `Application["MyData"]` isn't known at compile-time, isn't it known that I'm trying to cast from `List<MyType>` to `IQueryable<MyType>`, which is not valid? Why don't I get a compiler error in this case?

Original source