skip to content

In C#, IEnumerable<T> is covariant, so why does a List<int> not convert to IEnumerable<object>?

level: seniorimportance: should knowfreq 40%

answer

  1. same object, same bits
  2. what an int would need first
  3. reference conversions only
  4. a type parameter with no class constraint

basics

~20 s

Variance conversions are reference conversions that reuse the same object unchanged. Reading an int as object needs boxing, a new object per element, so variance applies only when the type argument is a reference type.

solid answer

~40 s

A covariant conversion such as `IEnumerable<string>` to `IEnumerable<object>` is a **reference conversion**: the same object is reused and every element it yields is already an object reference. `IEnumerable<int>` yields raw 32-bit values; treating one as `object` requires **boxing**, which allocates a new object, so no representation-preserving conversion exists. C# and the runtime therefore apply variance only when the type argument is a reference type: the implicit assignment fails with CS0266, an explicit cast compiles but throws `InvalidCastException`, and `list is IEnumerable<object>` is `false`. The same rule bites inside generic code: an unconstrained `T` might be a value type, so `IEnumerable<T>` to `IEnumerable<object>` is also CS0266 until you add `where T : class`. To get objects, project explicitly with `Cast<object>()` or `Select(x => (object)x)` and accept one box per element.

code

csharp · 15 lines
csharp
var orderIds = new List<int> { 101, 102 };
// IEnumerable<object> ids = orderIds;          // CS0266: variance never applies to a value-type argument

object boxedList = orderIds;
Console.WriteLine(boxedList is IEnumerable<int>);       // True
Console.WriteLine(boxedList is IEnumerable<object>);    // False: the runtime agrees with the compiler

IEnumerable<object> boxedIds = orderIds.Cast<object>(); // a new sequence that boxes each int
Console.WriteLine(string.Join(",", boxedIds));

var placed = new List<OrderPlaced> { new(1) };
object boxedEvents = placed;
Console.WriteLine(boxedEvents is IEnumerable<object>);  // True: OrderPlaced is a reference type

record OrderPlaced(int Id);

go deeper

for a junior

Recall that IEnumerable<string> converts to IEnumerable<object> but IEnumerable<int> does not, and that the difference is reference type versus value type.

for a middle

Explain that variance is a reference conversion that reuses the same object, while an int needs boxing into a new object, so no such conversion exists. Know the CS0266 error you get.

for a senior

Spot the generic-code version of the bug, fix it with where T : class or a generic consumer, and know that Cast<object>() returns the source unchanged when variance already applies but boxes value types.

for a principal

When designing shared helpers, decide whether to accept IEnumerable<object> or stay generic over T; the generic signature serves value-type callers without per-element allocation.

## What a variance conversion really is When `IEnumerable<T>` is declared with `out T`, C# allows an **implicit reference conversion** from `IEnumerable<string>` to `IEnumerable<object>`. A reference conversion never creates a new object and never changes any bits: the variable of the target type simply points at the same object. That works because every element a `List<string>` yields is already a reference, and a reference to a `string` is a valid reference to an `object`. Variance is only ever this kind of conversion. The C# specification defines it in terms of reference conversions between the type arguments, and the runtime implements it the same way when it checks a cast or an `is` test against a variant interface. ## Why int breaks the chain A `List<int>` stores and yields raw 32-bit integers, not references. Code that reads through `IEnumerable<object>` expects `IEnumerator<object>.Current` to return an object reference. Turning an `int` into an `object` is **boxing**: the runtime allocates a new heap object and copies the value into it. That is a representation-changing conversion, not a reference conversion, so there is no way to reuse the list as it is. So the rule is: **variance applies only when the type arguments involved are reference types.** For value-type arguments a variant interface behaves as if it were invariant. The rule is about the **type argument**, not about the type that implements the interface. A struct that implements `IEnumerable<string>` converts to `IEnumerable<object>` once it is boxed as the interface, because the elements it yields are `string` references. A record class whose elements are reference types converts too. Only the element type, `int` in this case, decides whether a reference conversion between the constructed interfaces exists. | Source | Target | Result | |---|---|---| | `List<string>` | `IEnumerable<object>` | implicit conversion, same object | | `List<OrderPlaced>` (a record class) | `IEnumerable<object>` | implicit conversion, same object | | `List<int>` | `IEnumerable<object>` | CS0266 on assignment | | `(IEnumerable<object>)(object)ints` | explicit cast | compiles, throws `InvalidCastException` | | `List<int>` tested with `is IEnumerable<object>` | type test | `false` at run time | The compiler and the runtime agree: the assignment is rejected at compile time with CS0266, and the run-time type test says no as well. ## The same rule inside generic code The rule also applies to type parameters. In a method such as ```csharp static IEnumerable<object> AsObjects<T>(IEnumerable<T> items) => items; ``` the compiler reports CS0266, because `T` could be `int`. Adding `where T : class` tells the compiler that `T` is always a reference type, and the same body then compiles: ```csharp static IEnumerable<object> AsObjects<T>(IEnumerable<T> items) where T : class => items; ``` This is a common surprise in shared helpers that work for every caller's reference types and then reject a caller that passes a struct. ## Getting objects out of value-type sequences When code really needs `IEnumerable<object>` from a `List<int>`, it must produce new objects: - **`ints.Cast<object>()`** returns a lazy sequence that boxes each element as it is enumerated. When the source already is an `IEnumerable<object>`, such as a `List<string>`, `Enumerable.Cast` returns the source itself because the variance conversion already applies. - **`ints.Select(x => (object)x)`** does the same with an explicit projection. - **A generic consumer**, such as `void Log<T>(IEnumerable<T> values)`, avoids the conversion entirely and never boxes for this reason. Each of the first two options allocates one box per element per enumeration. How much that costs and where else boxing hides is covered in the lesson on boxing and unboxing; for variance the point is only that boxing is a new object, so it can never be a variance conversion. ## Points to make in an interview 1. Covariance and contravariance are reference conversions: same object, no allocation. 2. A value-type element would need boxing, so variance never applies to value-type type arguments. 3. The compiler reports CS0266, an explicit cast throws `InvalidCastException`, and `is` returns `false`. 4. Inside generic code, add `where T : class` to make variance available through `T`. 5. To get objects anyway, project with `Cast<object>()` or `Select`, and accept the boxing.

  • A generic helper returns IEnumerable<T> as IEnumerable<object> and fails with CS0266; how do you fix it?
    Constrain the type parameter with `where T : class`. Without it `T` might be a value type, for which no variance conversion exists, so the compiler refuses. With the constraint `T` is known to be a reference type and the covariant conversion compiles with no copy.
  • Does Cast<object>() over a List<string> create a new boxed sequence too?
    No. `Enumerable.Cast<TResult>` first tests whether the source already is an `IEnumerable<TResult>`; a `List<string>` is an `IEnumerable<object>` through covariance, so `Cast<object>()` returns the same list. Only sources that fail that test, such as a `List<int>`, get the iterator that converts each element.
  • What does an explicit cast (IEnumerable<object>)(object)orderIds do when orderIds is a List<int>?
    It compiles, because CS0266 reports that an explicit conversion exists between those types, but the runtime cast fails with `InvalidCastException`. A `List<int>` implements `IEnumerable<int>`, and variance does not relate that to `IEnumerable<object>`.

  • Covariance boxes each int automatically when IEnumerable<int> is used as IEnumerable<object>.
  • List<int> fails only because int is a struct that cannot implement interfaces.
  • An explicit cast to IEnumerable<object> works at run time even if the implicit one does not compile.
  • An unconstrained T in a generic method gets the same variance as a reference type.
  • Cast<object>() always allocates a new sequence, even for a List<string>.