Compile error when assigning IQueryable<int> to IQueryable<object>

152 views Asked by At

Why the compiler doesn't allow to assign ints to objects?

IQueryable<object> objects = null;
IQueryable<int> ints = null;
objects = ints;
1

There are 1 answers

5
Nathan Taylor On

Implicit type conversion (a function of covariance) does not apply to all generics. SomeGeneric<ValueType> is not derived from to SomeGeneric<Reference> and thus, it is not valid to cast it even if there is a already an implicit conversion for the type parameters (in this case, boxing).

If you are in C# 4.0, a generic interface can be defined as covariant using ISomeGeneric<out T> and provided that the generic arguments are derived from one another, then you can cast. If the generic arguments are not derived, it is not possible to cast.