skip to content

In C#, DomainEvent[] events = placed; compiles when placed is an OrderPlaced[], so why does storing an OrderCancelled into events throw?

level: seniorimportance: should knowfreq 45%

answer

  1. arrays predate generic variance
  2. the object keeps its real type
  3. a check on every store
  4. Span<T> checks the array up front

basics

~10 s

Arrays of reference types are covariant, so the assignment reuses the same OrderPlaced[] object. The runtime type-checks stores into it, and putting an OrderCancelled there throws ArrayTypeMismatchException at run time, not a compile error.

solid answer

~40 s

C# keeps the runtime's **array covariance**: an `OrderPlaced[]` converts implicitly to `DomainEvent[]` (or `object[]`) whenever the element types are reference types. No copy is made, so `events.GetType()` is still `OrderPlaced[]`. The static type would allow storing any `DomainEvent`, so the runtime type-checks reference stores against the array's real element type and throws `ArrayTypeMismatchException` ("Attempted to access an element as a type incompatible with the array.") for an `OrderCancelled`. The compiler cannot catch it. Reading stays safe, so a method that only reads should take `IReadOnlyList<DomainEvent>` or `ReadOnlySpan<DomainEvent>`. `new Span<DomainEvent>(events)` throws the same exception up front, and since C# 14 a call that prefers a `Span<T>` overload over an `IEnumerable<T>` one can now hit that throw with a covariant array.

code

csharp · 22 lines
csharp
OrderPlaced[] placed = { new(1), new(2) };
DomainEvent[] events = placed;                  // array covariance: compiles, no copy
Console.WriteLine(events.GetType());            // the object is still an OrderPlaced[]

events[0] = new OrderPlaced(3);                 // fine: the element really is an OrderPlaced
try
{
    events[1] = new OrderCancelled(4);          // the runtime's store check rejects it
}
catch (ArrayTypeMismatchException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

ReadOnlySpan<DomainEvent> read = events;        // reading through a covariant array is safe
Console.WriteLine(read[0]);
try { Span<DomainEvent> write = new(events); }  // Span<T> checks the exact array type up front
catch (ArrayTypeMismatchException) { Console.WriteLine("Span<DomainEvent>: ArrayTypeMismatchException"); }

abstract record DomainEvent(int Id);
record OrderPlaced(int Id) : DomainEvent(Id);
record OrderCancelled(int Id) : DomainEvent(Id);

go deeper

for a junior

Recall that an array of a derived class can be assigned to an array of its base class, and that storing the wrong type into it fails when the code runs, not when it compiles.

for a middle

Explain that the conversion keeps the original array object and that the runtime checks each reference store, throwing ArrayTypeMismatchException. Contrast it with List<T>, which is invariant.

for a senior

Diagnose the exception from a stack trace back to a caller's more derived array, harden APIs with read-only parameter types, and know that Span<T> construction and C# 14 span overload preference hit the same check.

for a principal

Set the API rule that writable buffers are passed as exact-typed arrays or generic collections, never as covariant base-type arrays, so the failure is a compile error rather than an exception at run time.

## Arrays are covariant, generics are not C# arrays of reference types are **covariant**: if `OrderPlaced` derives from `DomainEvent`, an `OrderPlaced[]` converts implicitly to `DomainEvent[]` and to `object[]`. This rule comes from the runtime's array type system and has been part of C# since its first version, long before `out` and `in` on generic interfaces existed. Generic classes such as `List<T>` never got the same treatment; they are invariant. The conversion is a **reference conversion**: no new array is created. After `DomainEvent[] events = placed;`, both variables point at one object whose runtime type is still `OrderPlaced[]`, and `events.GetType()` prints `OrderPlaced[]`. ## Where the hole is, and how the runtime plugs it The static type `DomainEvent[]` says any `DomainEvent` may be stored. The object can only hold `OrderPlaced` references. To keep the heap type-safe, the runtime **type-checks reference stores into the array** against the array's actual element type: 1. `events[0] = new OrderPlaced(3);` passes the check: the value really is an `OrderPlaced`. 2. `events[1] = new OrderCancelled(4);` fails it, and the runtime throws `ArrayTypeMismatchException` with the message "Attempted to access an element as a type incompatible with the array." The exception is thrown at **run time**, when the store executes. The compiler accepted the code because, by the static types, it is legal. This is the key contrast with generic variance, where `out T` and `in T` are checked when the interface is declared, so a variant interface can never produce such an exception. | Operation on `events` (really an `OrderPlaced[]`) | Outcome | |---|---| | Read `events[0]` as `DomainEvent` | always safe | | Store an `OrderPlaced` | passes the run-time check | | Store an `OrderCancelled` | `ArrayTypeMismatchException` | | `int[]` to `object[]` | CS0029; value-type arrays are not covariant | Value-type arrays never take part: an `int[]` is not an `object[]`, because the elements are raw values, not references, and the compiler rejects the conversion with CS0029. ## Spans meet covariant arrays `Span<T>` gives direct, unchecked write access to an array's memory, so it cannot rely on a per-store check. Instead, its constructor checks once: when `T` is a reference type and the array's runtime type is not exactly `T[]`, `new Span<DomainEvent>(events)` throws `ArrayTypeMismatchException` immediately. `ReadOnlySpan<T>` has no such check, because reading through a covariant array is always safe, so `ReadOnlySpan<DomainEvent> read = events;` works. That difference matters more since **C# 14**, which added implicit conversions from arrays to spans and prefers them in overload resolution. A method group with both `R<T>(IEnumerable<T>)` and `R<T>(Span<T>)` used to bind the `IEnumerable<T>` overload for an array argument; with C# 14 it binds the `Span<T>` overload, and passing a covariant array now throws `ArrayTypeMismatchException` inside the implicit array-to-span conversion. The compiler team lists this as a C# 14 breaking change; the fixes are calling `.AsEnumerable()` at the call site or, for API authors, offering a `ReadOnlySpan<T>` overload, which the new rules prefer over `Span<T>`. ## Preventing it in real code - **Read-only parameters:** a method that only reads should accept `IReadOnlyList<DomainEvent>`, `IEnumerable<DomainEvent>` or `ReadOnlySpan<DomainEvent>`, none of which can store. - **Exact element types:** a method that fills an array should allocate it itself, `new DomainEvent[n]`, rather than write into an array it was handed. - **Know who owns the array:** if a caller passed an `OrderPlaced[]` as `DomainEvent[]`, every store your method makes is checked against the caller's element type, not yours. - **Prefer generic collections for writable APIs:** `List<DomainEvent>` is invariant, so the mistake becomes a compile error instead of an exception. ## Tracing the exception back to its cause The stack trace points at the store, but the cause is usually far away, where a more derived array was created and handed over as a base-type array. 1. Inspect `events.GetType()` in the debugger or a log line; it shows the array's real element type. 2. Follow that array back to its allocation, typically a `new OrderPlaced[n]` or a `ToArray()` call on an `IEnumerable<OrderPlaced>`. 3. Decide whether the receiving method should stop writing, or the caller should pass an array of the exact element type. ## How to answer it Say that arrays of reference types are covariant for historical reasons, that the conversion keeps the original array object, and that the runtime type-checks stores and throws `ArrayTypeMismatchException` on a mismatch. Contrast it with generic variance, which is proven safe at compile time, and mention the `Span<T>` constructor check as the place modern code meets the same rule.

  • Why does new ReadOnlySpan<DomainEvent>(events) succeed where new Span<DomainEvent>(events) throws?
    `Span<T>` allows writes with no per-store check, so its constructor throws `ArrayTypeMismatchException` when `T` is a reference type and the array is not exactly `T[]`. `ReadOnlySpan<T>` can only read, and reading an `OrderPlaced` as a `DomainEvent` is always safe, so it has no such check.
  • Under C# 14, why can a call that worked before now throw for a covariant array argument?
    C# 14 added implicit array-to-span conversions and prefers them, so a call with both `IEnumerable<T>` and `Span<T>` overloads now binds the span one. Converting an `OrderPlaced[]` typed as `DomainEvent[]` to `Span<DomainEvent>` throws `ArrayTypeMismatchException`. Call `.AsEnumerable()`, or have the API offer a `ReadOnlySpan<T>` overload.
  • Is int[] to object[] allowed by the same rule?
    No. Array covariance applies only to reference element types, because the conversion must reuse the same array of references. An `int[]` holds raw values, so the compiler rejects the conversion with CS0029.

  • The compiler rejects storing an OrderCancelled into a DomainEvent[] variable.
  • Converting OrderPlaced[] to DomainEvent[] copies the elements into a new array.
  • Array covariance works for value types too, so int[] converts to object[].
  • A failed store into a covariant array throws InvalidCastException.
  • Generic interfaces such as IEnumerable<out T> can also throw ArrayTypeMismatchException on writes.

Assumes C# 14 on .NET 10; array covariance is as old as C#, but the Span<T> overload preference that throws on covariant arrays came with C# 14's implicit span conversions.