skip to content

In C#, why does interface IProducer<out TEvent> with a Publish(TEvent e) method fail with CS1961, and how do you fix it?

level: seniorimportance: should knowfreq 32%

answer

  1. the compiler proves it at declaration
  2. input versus output positions
  3. a callback parameter flips the sign
  4. split the reading half from the writing half

basics

~20 s

A covariant (out) type parameter may appear only in output positions; a method parameter is an input position, so Publish(TEvent) gets CS1961. Split the interface into an out reading interface and an in writing interface.

solid answer

~40 s

The compiler checks every member of a variant interface for **variance safety**. An `out TEvent` must be *output-safe* wherever it appears: return types and get-only properties are fine, while a by-value parameter needs input safety, so `void Publish(TEvent e)` gives CS1961, "The type parameter 'TEvent' must be contravariantly valid on 'IProducer<TEvent>.Publish(TEvent)'. 'TEvent' is covariant." `ref` and `out` parameters and get-set properties need both directions, so they are invalid for either annotation. Positions flip inside another variant type: `void Subscribe(Action<TEvent> handler)` is legal in a covariant interface, because `TEvent` is an input of an input. The usual fix is to split the type: `IEventSource<out TEvent>` with `Next()` and `Subscribe`, `IEventSink<in TEvent>` with `Publish`, and an invariant `IProducer<TEvent>` that inherits both.

code

csharp · 5 lines
csharp
interface IProducer<out TEvent>
{
    TEvent Next();
    void Publish(TEvent e);
}

go deeper

for a junior

Recall that out type parameters may only be returned and in type parameters may only be accepted, and that the compiler error for breaking this is CS1961.

for a middle

Explain the position table: return types and getters are outputs, parameters and setters are inputs, and ref, out and get-set members need both. Read the CS1961 message to tell which rule broke.

for a senior

Reason about nested positions such as Action<TEvent> parameters, and fix CS1961 by splitting an interface into reading and writing halves rather than deleting the variance annotation.

for a principal

Treat CS1961 as design feedback: an interface that both produces and consumes a type should be invariant or split by direction before it ships.

## What CS1961 protects Declaring `interface IProducer<out TEvent>` promises that an `IProducer<OrderPlaced>` can be used as an `IProducer<DomainEvent>`. That promise is only safe if `TEvent` values flow **out** of the interface and never **in**. If `Publish(TEvent e)` were allowed, code holding the `IProducer<DomainEvent>` view could call `Publish(new OrderCancelled(4))` on a producer that only handles `OrderPlaced`. C# does not wait for that to go wrong at run time. The compiler checks every member of an interface or delegate that has variant type parameters, and reports **CS1961** on the first member that uses a type parameter in the wrong position. The SDK's message for the broken producer is: > Invalid variance: The type parameter 'TEvent' must be contravariantly valid on 'IProducer<TEvent>.Publish(TEvent)'. 'TEvent' is covariant. "Contravariantly valid" means "safe in an input position", which an `out` parameter is not. ## Input and output positions | Where the type parameter appears | Position | Allowed for | |---|---|---| | Method return type | output | `out` | | Get-only property | output | `out` | | By-value method parameter | input | `in` | | Set-only property | input | `in` | | Get-and-set property | both | neither | | `ref` or `out` parameter | both | neither | | Constraint of a method type parameter, `where U : TEvent` | input | `in` | | Base interface's type argument | follows that interface's variance | depends | Positions compose when the type parameter is nested inside another variant type: - `Func<TEvent>` as a **return type** keeps `TEvent` in an output position, so it is fine for `out`. - `Action<TEvent>` as a **parameter** puts `TEvent` in the input slot of an input, which is an output position again. `void Subscribe(Action<TEvent> handler)` therefore compiles inside `IProducer<out TEvent>`, and it is sound: the producer calls the handler with its own events. - `IEnumerable<TEvent>` as a return type is output-of-output, still fine. Two more details come straight from the compiler's variance check. A default interface method body does not exempt a member: `void Log(TEvent e) { }` with a body is still CS1961. Static members that are neither `abstract` nor `virtual` are skipped by the check since C# 9, because they can never be called through a converted interface reference. ## Delegates and events follow the same rules A generic delegate is checked like an interface with one method, its `Invoke`. Declaring `delegate void Sink<out T>(T item);` fails with CS1961 on `Sink<T>.Invoke(T)`, which is why the base class library declares `Action<in T>` and `Func<in T, out TResult>` the way it does. An interface event is treated as an input position, yet `event Action<TEvent> Raised;` still compiles inside `IProducer<out TEvent>`, for the same sign-flip reason as `Subscribe(Action<TEvent>)`. ## Fixing the producer There are three honest options. 1. **Split the interface by direction.** Put the producing members in `IEventSource<out TEvent>`, the consuming members in `IEventSink<in TEvent>`, and declare `interface IProducer<TEvent> : IEventSource<TEvent>, IEventSink<TEvent>` without a variance modifier. Code that only reads asks for `IEventSource<DomainEvent>` and accepts any producer; code that publishes asks for `IEventSink<OrderPlaced>` and accepts a general sink. This mirrors how the base class library separates `IReadOnlyList<out T>` from the invariant `IList<T>`. 2. **Drop the annotation.** If the type really reads and writes the same `TEvent`, it is invariant by nature; leave `out` off and accept exact type arguments only. 3. **Move the input to a method type parameter.** `void Publish<TOther>(TOther e) where TOther : ...` sometimes fits, but a constraint that mentions `TEvent` is itself an input position, so `where TOther : TEvent` brings CS1961 back. ```csharp interface IEventSource<out TEvent> { TEvent Next(); void Subscribe(Action<TEvent> handler); } interface IEventSink<in TEvent> { void Publish(TEvent e); } interface IProducer<TEvent> : IEventSource<TEvent>, IEventSink<TEvent> { } ``` A base interface counts too: `interface IProducer<out TEvent> : IEventSink<TEvent>` fails with CS1961 because the covariant `TEvent` would flow into the contravariant base's input slot. ## Diagnosing it quickly - Read the message's last two words: "is covariant" means an `out` parameter landed in an input position; "is contravariant" means an `in` parameter landed in an output position. - "Must be invariantly valid" means the member needs both directions, as with `ref`, `out` or a get-set property. - Fix the design rather than the symptom: each CS1961 is the compiler telling you the interface both produces and consumes that type.

  • Why is bool TryRead(out TEvent value) rejected in a covariant interface even though it returns a value?
    An `out` parameter is passed by reference, and the compiler requires a by-reference parameter's type to be safe in both directions. The message says `TEvent` "must be invariantly valid". Return `TEvent?` and signal "nothing read" with null instead; a tuple return such as `(bool, TEvent)` does not help, because `ValueTuple`'s type parameters are invariant and the compiler again demands invariant validity.
  • Why is void Subscribe(Action<TEvent> handler) legal inside IProducer<out TEvent>?
    `Action<in T>` is contravariant, and the whole `Action<TEvent>` is a parameter, so `TEvent` sits in an input position of an input position, which is an output position. Data flows from the producer into the handler, the same direction as `Next()`.

  • A default interface method body lets a covariant TEvent appear as a parameter.
  • CS1961 can be silenced by marking the member virtual.
  • Any parameter that mentions TEvent, including Action<TEvent>, is illegal in an out interface.
  • An out parameter counts as an output position, so it is fine for a covariant type parameter.
  • CS1961 is reported where the interface is used, not where it is declared.