In C#, why can a List<OrderPlaced> be passed as IEnumerable<DomainEvent> but not assigned to a List<DomainEvent>?
answer
- declared on the type, not the argument
- which members take T in
- out on IEnumerable<T>
- classes never carry in or out
basics
~10 sIEnumerable<T> declares T as out (covariant) and only hands values out, so OrderPlaced items read safely as DomainEvent. List<T> is a class, classes are always invariant, and its Add(T) would otherwise accept any DomainEvent.
solid answer
~40 sVariance is declared on a generic type's parameter, not inferred from the type arguments. `IEnumerable<T>` is declared `IEnumerable<out T>`: `T` only comes out of it (through `GetEnumerator()` and `IEnumerator<T>.Current`), so a sequence of `OrderPlaced` can be read as a sequence of `DomainEvent`, and the compiler allows an implicit reference conversion with no copy. `List<T>` is a class, and C# allows `in` and `out` only on interface and delegate type parameters (CS1960 otherwise), so `List<OrderPlaced>` to `List<DomainEvent>` fails with CS0029. It would be unsafe anyway: `Add(T)` and the indexer setter would let a caller store an `OrderCancelled` in a list its owner believes holds only `OrderPlaced`. When a method needs a count or an index, accept `IReadOnlyList<DomainEvent>`, which is covariant too.
code
csharp · 21 linesvar placed = new List<OrderPlaced> { new(1), new(2) };
Audit.LogAll(placed); // List<OrderPlaced> -> IEnumerable<DomainEvent>
IReadOnlyList<DomainEvent> view = placed; // IReadOnlyList<out T> is covariant too
Console.WriteLine(view[1]);
// List<DomainEvent> all = placed; // CS0029: List<T> is a class, so it is invariant
var copy = new List<DomainEvent>(placed); // a new list, not a view of the old one
copy.Add(new OrderCancelled(3));
Console.WriteLine($"{placed.Count} {copy.Count}");
static class Audit
{
public static void LogAll(IEnumerable<DomainEvent> events)
{
foreach (var e in events) Console.WriteLine($"audit {e.Id}");
}
}
abstract record DomainEvent(int Id);
record OrderPlaced(int Id) : DomainEvent(Id);
record OrderCancelled(int Id) : DomainEvent(Id);go deeper
Recall that IEnumerable<T> is declared with out T and List<T> is invariant, and know the compile error you get when you try to assign a list of a derived type to a list of its base.
Explain why: out lets T appear only in output positions, while List<T> takes T through Add and its indexer. Name the covariant read-only interfaces as the fix for method parameters.
Show that the conversion is a reference conversion with no copy, that an explicit IList<DomainEvent> cast compiles yet throws InvalidCastException, and steer APIs toward IEnumerable<T> or IReadOnlyList<T> parameters.
Frame parameter types as a contract choice: accepting the narrowest covariant interface widens what callers can pass, while demanding List<T> forces copies and couples callers to one concrete collection.
## Two conversions that look alike When `OrderPlaced` derives from `DomainEvent`, C# has an implicit reference conversion from `OrderPlaced` to `DomainEvent`. Whether that relationship carries over to a **constructed generic type** such as `IEnumerable<OrderPlaced>` or `List<OrderPlaced>` is decided by the generic type's own declaration, not by the type arguments. That property is called **variance**, and each type parameter has one of three kinds: - **Covariant** (`out T`): `G<OrderPlaced>` converts to `G<DomainEvent>`, in the same direction as the element types. - **Contravariant** (`in T`): `G<DomainEvent>` converts to `G<OrderPlaced>`, in the opposite direction. - **Invariant** (no modifier, the default): no conversion either way; only the exact type argument fits. | Target type | Does `List<OrderPlaced>` convert implicitly? | Why | |---|---|---| | `IEnumerable<DomainEvent>` | Yes | declared `IEnumerable<out T>` | | `IReadOnlyList<DomainEvent>` | Yes | declared `IReadOnlyList<out T>` | | `IList<DomainEvent>` | No, CS0266 | `IList<T>` is invariant | | `List<DomainEvent>` | No, CS0029 | classes are invariant | ## Why IEnumerable<T> may be covariant The runtime declares `public interface IEnumerable<out T> : IEnumerable`. Its only member, `GetEnumerator()`, returns `IEnumerator<T>`, which is also declared with `out T` and hands elements out through `Current`. Nothing on either interface accepts a `T` as input. A method that sees the list as `IEnumerable<DomainEvent>` can only read elements and treat each one as a `DomainEvent`, and every `OrderPlaced` is one. The base class library uses the same declaration wherever a type only produces values: `IEnumerator<out T>`, `IReadOnlyCollection<out T>`, `IReadOnlyList<out T>` and LINQ's `IGrouping<out TKey, out TElement>` are all covariant. That is why a `List<OrderPlaced>` flows into so many read-only APIs without any conversion code: the conversion is decided once, on the interface, and every implementing type benefits automatically. The compiler holds the interface to that promise: a type parameter marked `out` may appear only in output positions, such as return types and get-only properties, and using it as a method parameter type is error CS1961. The conversion itself is a plain **reference conversion**. No wrapper is created and nothing is copied: the parameter refers to the very same `List<OrderPlaced>` object, so `ReferenceEquals(events, placed)` is `true`, and casting the `IEnumerable<DomainEvent>` back to `List<OrderPlaced>` succeeds. ## Why List<T> stays invariant Two separate rules close the door. 1. **Only interfaces and delegates may declare variance.** Writing `class EventBatch<out T>` fails with CS1960: "Invalid variance modifier. Only interface and delegate type parameters can be specified as variant." Classes and structs are always invariant, so `List<T>` could not opt in even if its authors wanted it to. 2. **A covariant list would be unsound.** `List<T>` has `Add(T)`, `Insert(int, T)` and a setter on its indexer, all of them input positions. If a `List<OrderPlaced>` were a `List<DomainEvent>`, a caller could add an `OrderCancelled` to a list that its owner still reads as `OrderPlaced` items, and the type system would no longer describe what the list holds. The same reasoning makes `IList<T>` and `ICollection<T>` invariant interfaces: they accept `T` through `Add` and the indexer setter. An explicit cast such as `(IList<DomainEvent>)placed` does compile, because CS0266 reports that an explicit conversion exists, but it throws `InvalidCastException` at run time, since `List<OrderPlaced>` does not implement `IList<DomainEvent>`. ## Getting a DomainEvent view of the list - Accept **`IEnumerable<DomainEvent>`** when the method only iterates. - Accept **`IReadOnlyList<DomainEvent>`** or **`IReadOnlyCollection<DomainEvent>`** when it needs `Count` or an indexer; both are declared with `out T`, and `List<T>` implements both. - Make the method **generic**, for example `void Archive<TEvent>(List<TEvent> events) where TEvent : DomainEvent`, when it truly needs the concrete list type. - **Copy** with `new List<DomainEvent>(placed)` when the callee must add events of other types; the copy is a separate list, so adding to it leaves the original untouched. ```csharp var placed = new List<OrderPlaced> { new(1), new(2) }; IEnumerable<DomainEvent> all = placed; // covariant interface: OK IReadOnlyList<DomainEvent> view = placed; // covariant interface: OK // List<DomainEvent> list = placed; // CS0029: List<T> is invariant var copy = new List<DomainEvent>(placed); // independent list of the same events ``` ## How to answer it in an interview 1. Say that variance is declared per type parameter with `out` or `in`, and only interfaces and delegates may declare it. 2. Explain that `IEnumerable<T>` is `out` because it only produces values, so reading `OrderPlaced` items as `DomainEvent` is always safe. 3. Explain that `List<T>` is a class, therefore invariant, and that its `Add` would break type safety if it were not. 4. Offer the practical fix: depend on `IEnumerable<T>` or `IReadOnlyList<T>` instead of `List<T>` in method signatures.
- Which read-only interfaces let a method take a List<OrderPlaced> as indexable DomainEvent data?`IReadOnlyList<out T>` and `IReadOnlyCollection<out T>` are both covariant, and `List<T>` implements them, so `IReadOnlyList<DomainEvent> view = placed;` compiles with no copy. `IList<T>` and `ICollection<T>` are invariant because `Add` and the indexer setter take `T` as input.
- Does passing the list as IEnumerable<DomainEvent> copy or wrap it?Neither. It is an implicit reference conversion, so the parameter holds the same `List<OrderPlaced>` object. Mutations made through the original list are visible through the `IEnumerable<DomainEvent>`, and a cast back to `List<OrderPlaced>` succeeds at run time.
- Could you declare your own class EventBatch<out T> to get covariance?No. The compiler rejects it with CS1960, because only interface and delegate type parameters can be variant. Declare a covariant interface such as `IEventBatch<out T>` with output-only members and have the class implement it.
- List<OrderPlaced> is a List<DomainEvent> because OrderPlaced derives from DomainEvent.
- Passing the list as IEnumerable<DomainEvent> copies its elements into a new sequence.
- List<T> could be covariant; the BCL simply never added out to it.
- IList<T> is covariant because List<T> implements both IList<T> and IEnumerable<T>.
- Casting with (List<DomainEvent>)placed compiles and works at run time.