mellamokb
mellamokb

Reputation: 56779

Incompatible Double Casting - Not Detected by Compiler

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?

Upvotes: 3

Views: 112

Answers (2)

Ken Kin
Ken Kin

Reputation: 4703

It just because IQueryable<T> is an interface.

var anywayListOfMyType=
    (IWhatsoever)(IFormatProvider)(IIntellisenseBuilder)new List<MyType>();

would compiles.

p.s.

IWhatsoever doesn't really exist.

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149050

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.

Upvotes: 9

Related Questions