In C#, why can an IHandler<DomainEvent> declared with in TEvent be used where an IHandler<OrderPlaced> is required?
answer
- the conversion runs the other way
- a type that only consumes
- parameters, never return values
- Action<in T> and IComparer<in T>
basics
~20 sThe in modifier makes TEvent contravariant: the handler only accepts events, and code that handles any DomainEvent can safely handle an OrderPlaced. The conversion runs from base to derived, as with Action<in T> and IComparer<in T>.
solid answer
~40 s`in` on a type parameter declares it **contravariant**: `IHandler<DomainEvent>` converts implicitly to `IHandler<OrderPlaced>`, the reverse of the element types' direction. It is safe because `TEvent` only flows into the handler, through `Handle(TEvent e)`; whoever calls `Handle` through the `IHandler<OrderPlaced>` view must pass an `OrderPlaced`, and the audit handler accepts any `DomainEvent`. The compiler enforces the promise: returning `TEvent` from a member of an `in` interface is CS1961. The BCL uses the same rule for `Action<in T>`, `Predicate<in T>`, `Comparison<in T>`, `IComparer<in T>`, `IEqualityComparer<in T>`, `IComparable<in T>` and the parameters of `Func<in T, out TResult>`, which is why an `IComparer<DomainEvent>` can order a `SortedSet<OrderPlaced>`.
code
csharp · 23 linesIHandler<DomainEvent> audit = new AuditHandler();
IHandler<OrderPlaced> onPlaced = audit; // in TEvent: base-type handler where a derived one is needed
onPlaced.Handle(new OrderPlaced(42));
Action<DomainEvent> log = e => Console.WriteLine($"log {e.Id}");
Action<OrderPlaced> logPlaced = log; // Action<in T>
logPlaced(new OrderPlaced(7));
Func<DomainEvent, string> describe = e => $"event {e.Id}";
Func<OrderPlaced, object> loose = describe; // Func<in T, out TResult>: both directions at once
Console.WriteLine(loose(new OrderPlaced(9)));
var byId = Comparer<DomainEvent>.Create((a, b) => a.Id.CompareTo(b.Id));
var queue = new SortedSet<OrderPlaced>(byId) { new(3), new(1) }; // IComparer<in T>
Console.WriteLine(string.Join(",", queue.Select(o => o.Id)));
interface IHandler<in TEvent> { void Handle(TEvent e); }
class AuditHandler : IHandler<DomainEvent>
{
public void Handle(DomainEvent e) => Console.WriteLine($"audit {e.Id}");
}
abstract record DomainEvent(int Id);
record OrderPlaced(int Id) : DomainEvent(Id);go deeper
Recall that in on an interface or delegate type parameter lets a handler for a base type be used where a handler for a derived type is required, and name Action<in T> as an example.
Explain the data-flow argument: the type parameter only enters through parameters, so callers of the narrower view can only pass values the wider implementation accepts. Know that CS1961 guards the declaration.
Use contravariance to register one general handler or comparer for many event types, and know its traps: value-type arguments get no variance, and combining variant delegates throws ArgumentException at run time.
Decide when a shared handler or comparer interface should be declared in from its first release, since general-purpose implementations then plug in without adapter classes across every team that consumes it.
## Contravariance in one sentence A type parameter declared with **`in`** is **contravariant**: if `OrderPlaced` derives from `DomainEvent`, then `IHandler<DomainEvent>` converts implicitly to `IHandler<OrderPlaced>`. The arrow between the generic types points the opposite way from the arrow between the type arguments, which is why contravariance first looks backward. The `in` here has nothing to do with the `in` parameter modifier that passes an argument by read-only reference. On a generic type parameter it is a variance annotation, allowed only on interfaces and delegates. ## Why the handler conversion is safe ```csharp interface IHandler<in TEvent> { void Handle(TEvent e); } class AuditHandler : IHandler<DomainEvent> { public void Handle(DomainEvent e) { } } IHandler<OrderPlaced> onPlaced = new AuditHandler(); // compiles onPlaced.Handle(new OrderPlaced(42)); ``` Follow the data. Code that holds `onPlaced` sees an `IHandler<OrderPlaced>`, so the compiler only lets it pass an `OrderPlaced` to `Handle`. The object behind it is an `AuditHandler`, whose `Handle` accepts any `DomainEvent`. Every `OrderPlaced` is a `DomainEvent`, so no call through the narrower view can hand the handler something it cannot process. One general-purpose handler can therefore be registered wherever a specific one is expected, with no adapter class. The conversion is again a plain reference conversion: `onPlaced` and the `AuditHandler` instance are the same object, so no wrapper is allocated and the handler's state is shared by every view of it. Calling `Handle` through `onPlaced` dispatches straight to `AuditHandler.Handle`. The reverse fails: an `IHandler<OrderPlaced>` cannot become an `IHandler<DomainEvent>`, because callers could then pass an `OrderCancelled` to a handler that only knows `OrderPlaced`. ## What the compiler checks An `in` type parameter may appear only in **input positions**: - as the type of an ordinary (by-value) method parameter; - as the type of a set-only property; - as a type argument in another variant type, following that type's own variance rules. It may not be a return type, a get-only property type, or a `ref` or `out` parameter type. Writing `interface IHandler<in TEvent> { TEvent Last { get; } }` fails with CS1961: "Invalid variance: The type parameter 'TEvent' must be covariantly valid on 'IHandler<TEvent>.Last'. 'TEvent' is contravariant." The check happens entirely at compile time, on the interface declaration, so a variant interface can never be written in a way that makes the conversion unsafe. ## Where .NET already uses in | Type | Declaration | Conversion it allows | |---|---|---| | `Action<T>` | `Action<in T>` | `Action<DomainEvent>` to `Action<OrderPlaced>` | | `Func<T, TResult>` | `Func<in T, out TResult>` | `Func<DomainEvent, string>` to `Func<OrderPlaced, object>` | | `Predicate<T>`, `Comparison<T>` | `in T` | a base-type test or comparison for a derived type | | `IComparer<T>` | `IComparer<in T>` | `IComparer<DomainEvent>` for a `SortedSet<OrderPlaced>` | | `IEqualityComparer<T>`, `IComparable<T>` | `in T` | one base-type comparer for many derived types | `Func<in T, out TResult>` shows that one type can carry both kinds: its parameters are contravariant and its result is covariant, so a single conversion can widen the result and narrow the argument at once. ## Limits worth knowing 1. **Reference types only.** Variance never applies when a type argument is a value type, so a handler for a struct event converts to nothing but itself. 2. **Interfaces and delegates only.** A class such as `AuditHandler` is not itself variant; the conversion comes from the interface it implements. 3. **Delegate combination needs identical runtime types.** An `Action<DomainEvent>` stored in an `Action<OrderPlaced>` variable still has the runtime type `Action<DomainEvent>`, so combining it with a real `Action<OrderPlaced>` using `+` compiles but throws `ArgumentException` ("Delegates must be of the same type.") when it runs. 4. **Constraints are allowed.** `interface IHandler<in TEvent> where TEvent : DomainEvent` is legal; the constraint limits which type arguments are permitted, and variance still applies between them. ## How to answer it - Name the modifier and the direction: `in` makes the parameter contravariant, so base-type implementations stand in for derived-type requirements. - Justify it by data flow: the type parameter only goes into the object. - Give one BCL example, `IComparer<in T>` or `Action<in T>`, and mention CS1961 as the compiler's guard.
- An Action<DomainEvent> is stored in an Action<OrderPlaced> variable and then combined with another Action<OrderPlaced> using +; what happens?It compiles, because both operands have the static type `Action<OrderPlaced>`, but `Delegate.Combine` checks the runtime types and throws `ArgumentException` ("Delegates must be of the same type."). Variance changes which variable a delegate fits in, not its runtime type. Wrapping it first, as in `new Action<OrderPlaced>(logPlaced)`, creates a delegate whose runtime type is exactly `Action<OrderPlaced>`, and that one combines.
- Why may Func<DomainEvent, string> be assigned to Func<OrderPlaced, object>?`Func<in T, out TResult>` is contravariant in its argument and covariant in its result. Narrowing the argument from `DomainEvent` to `OrderPlaced` and widening the result from `string` to `object` are both safe, so the compiler allows one conversion that does both.
- Contravariance lets an IHandler<OrderPlaced> stand in where an IHandler<DomainEvent> is needed.
- in on a generic type parameter passes values by read-only reference, like the in parameter modifier.
- A contravariant TEvent can still be returned from a get-only property of the interface.
- SortedSet<OrderPlaced> needs a wrapper before it accepts an IComparer<DomainEvent>.
- Contravariance works for value-type events as long as they implement the same interface.