2

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

IQueryable<object> objects = null;
IQueryable<int> ints = null;
objects = ints;
AlbertK
  • 11,841
  • 5
  • 40
  • 36
  • You can cast it to `IQueryable` (OR) cast it to `IQueryable` before assigning. – Rahul Jun 20 '15 at 12:41
  • What is the target framework of your project? Is it by any chance .NET framework 3.5 or older? –  Jun 20 '15 at 13:03
  • @elgonzo, I use .Net Framework 4.5.1 – AlbertK Jun 20 '15 at 13:07
  • This is a duplicate, but for a practical answer to dealing with the issue, since you can assign an int to object, `objects = ints.Cast();` would work if you actually needed such a queryable. – Jon Hanna Jun 20 '15 at 16:27

1 Answers1

1

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.

Nathan Taylor
  • 24,423
  • 19
  • 99
  • 156
  • 1
    Well, the type parameter of IQuerable is covariant (i.e., `IQueryable`) according to its [documentation](http://msdn.microsoft.com/en-us/library/bb351562.aspx)... hmm... –  Jun 20 '15 at 13:00
  • Perhaps OP targets .NET 3.5 or older? –  Jun 20 '15 at 13:02
  • 1
    Check the edit I just made. Generic covariance does require that the type parameters are derivatives of each other. In the case of OP's question, Int does not inherit from Object and thus should not be convertible. – Nathan Taylor Jun 20 '15 at 13:03
  • Ahh, you are right... –  Jun 20 '15 at 13:09
  • 2
    Int32 _does_ inherit from Object, as far as the actual type hierarchy is concerned (it's why you can box them), but value types can't participate in covariance (because you can't have a type argument of boxed int, at least not in anything but _maybe_ C++/CLI). – Random832 Jun 20 '15 at 13:27
  • Thank you, @Random832, you're right. – Nathan Taylor Jun 20 '15 at 16:05