As lead of a shared C# events library, would you declare IProducer<TEvent> as out TEvent, knowing variance constrains every future member?
answer
- a promise about all future members
- adding it later is not neutral
- the read-only versus writable split
- type tests and overloads change
basics
~20 sDeclare out only for a pure producer that will stay one: callers gain free conversions, but no future member may take TEvent as input, and adding or removing out later changes overloads, type tests or compilation for callers.
solid answer
~50 sIt depends on whether the interface is, and will stay, a pure producer. Declaring `out TEvent` lets consumers pass an `IProducer<OrderPlaced>` wherever an `IProducer<DomainEvent>` is expected with no adapters, which is why `IEnumerable<out T>` and `IReadOnlyList<out T>` are covariant. The price is permanent: CS1961 forbids every later member that takes `TEvent` as input, so a future `Publish(TEvent)` needs a new interface. Changing your mind is not free either. Adding `out` in a later version changes which overload callers bind to and makes run-time `is` tests start returning `true`; removing it breaks every caller that relied on the conversion. My default is to split by direction from the first release, a covariant read interface and a contravariant write interface, keep the invariant combined type for implementers, and document the variance as part of the public contract.
code
csharp · 14 linesIProducer<OrderPlaced> orders = new OrderFeed();
Dashboard.Show(orders);
object any = orders;
Console.WriteLine(any is IProducer<DomainEvent>);
static class Dashboard
{
public static void Show(IProducer<DomainEvent> p) => Console.WriteLine("typed overload");
public static void Show(object p) => Console.WriteLine("object overload");
}
interface IProducer<TEvent> { TEvent Next(); } // version 1: invariant
class OrderFeed : IProducer<OrderPlaced> { public OrderPlaced Next() => new(1); }
abstract record DomainEvent(int Id);
record OrderPlaced(int Id) : DomainEvent(Id);go deeper
Recall that out on an interface lets a producer of a derived type be used as a producer of its base type, and that the interface can then never take that type as input.
Explain how CS1961 enforces the promise on every member, and why the base class library splits IReadOnlyList<out T> from IList<T> instead of making one interface variant.
Show what adding out later changes, overload binding and run-time type tests, and what removing it breaks, so variance is reviewed as an API change.
Own the decision: weigh consumer convenience against future input members, prefer a split read and write design from version 1, and make the annotation part of the documented, versioned contract.
## What the annotation commits you to Variance in C# is **declaration-site**: it is written once, on the interface or delegate, and every user inherits it. Declaring `interface IProducer<out TEvent>` is therefore a public promise that `TEvent` only ever flows out of the interface, and the compiler enforces it on **every member, forever**. Any later member that accepts `TEvent` as a by-value parameter, an `out` or `ref` parameter, a settable property or a method constraint fails with CS1961. You cannot add `Publish(TEvent e)` in version 2 without creating a new interface. The benefit is real. Consumers that depend on `IProducer<DomainEvent>` accept producers of any event type with no adapter classes and no copying, and generic code composes naturally with `IEnumerable<out T>` and `IReadOnlyList<out T>`, which the base class library declares covariant for the same reason. ## Changing your mind later has a cost in both directions **Adding `out` in a later version** looks like a pure widening, but it changes behaviour: 1. **Overload resolution can bind differently.** With overloads `Show(IProducer<DomainEvent>)` and `Show(object)`, a call with an `IProducer<OrderPlaced>` binds to `Show(object)` while the interface is invariant, and to the typed overload once it is covariant. Callers get the new behaviour silently when they recompile. 2. **Type tests change at run time.** `x is IProducer<DomainEvent>` is answered by the runtime from the interface's metadata, so it starts returning `true` for an `IProducer<OrderPlaced>`, even in caller assemblies that were never recompiled. 3. **Implementations can become ambiguous.** A class implementing both `IProducer<OrderPlaced>` and `IProducer<OrderCancelled>` gets no diagnostic, but viewed as `IProducer<DomainEvent>` it matches two implementations; the runtime picks one, and callers should not rely on which. **Removing `out`** is a breaking change: every caller that assigned an `IProducer<OrderPlaced>` to an `IProducer<DomainEvent>` stops compiling. | Choice at version 1 | What consumers gain | What you give up | |---|---|---| | Invariant `IProducer<TEvent>` | nothing extra | callers write adapters or generic methods | | Covariant `IProducer<out TEvent>` | free widening to base event types | no input members, ever, on this interface | | Split: `IEventSource<out TEvent>` plus `IEventSink<in TEvent>` | widening for readers and narrowing for writers | one more type to name and document | ## Facts that should shape the decision - **Who consumes it.** Many callers that hold collections or pipelines of base event types benefit most from covariance; a single internal caller may not need it. - **Event types that are structs.** Variance applies only to reference-type arguments, so producers of value-type events gain nothing from `out`. - **How likely writes are.** If anyone foresees a publish, acknowledge or replay member that takes `TEvent`, the type is not a pure producer, and declaring `out` now forces a new interface later. - **The base class library precedent.** .NET kept `IList<T>` invariant and added a separate `IReadOnlyList<out T>` rather than weakening either, the same split the table recommends. ## A defensible default for a shared library 1. Model direction explicitly from the first release: a covariant source interface for reading, a contravariant sink interface for writing, and an invariant combined interface for implementers. 2. Make consumers depend on the narrowest interface they need, so variance actually reaches them. 3. Treat the `in` and `out` annotations as part of the versioned public contract: never remove one, and review any addition for overload and type-test changes. 4. Keep value-type events on separate, invariant APIs, or make the consuming methods generic, so nobody expects conversions that cannot exist. ## A review checklist for variant interfaces - Does every member keep `TEvent` in a position the annotation allows, including members planned for the next release? - Are any implementers likely to implement two instantiations of the interface, which variance could make ambiguous? - Are the expected event types reference types, so the variance is usable at all? - Has the change been checked for overloads in consuming code that take both the interface and `object` or another base type? There is no universal answer, but there is a wrong process: adding or removing `out` casually in a minor release. Decide at version 1, write down why, and let the compiler's CS1961 checks hold every later member to it.
- Why does adding out to an existing interface affect callers that were not recompiled?Variance is recorded in the interface's metadata, and the runtime consults it when it evaluates casts and `is` tests. Once the new library version is loaded, a test such as `x is IProducer<DomainEvent>` starts succeeding for an `IProducer<OrderPlaced>`, whatever compiler built the calling assembly.
- How would you add a Publish(TEvent) member after shipping IProducer<out TEvent>?You cannot add it to that interface; CS1961 rejects it. Introduce a separate `IEventSink<in TEvent>` with `Publish`, plus an invariant interface that combines both if implementers need one, and let consumers that publish depend on the sink.
- Adding out to a published interface is a pure widening with no effect on existing callers.
- Variance can be dropped in a minor release without breaking anyone.
- Value-type event producers also benefit from declaring out TEvent.
- If a write member is needed later, it can simply be added to the covariant interface.
- A class implementing two variant interface instantiations gets a compiler error when they overlap.