A contravariant type parameter in C# allows a generic interface or delegate to accept a less derived (more general) type than the one explicitly specified. Denoted by theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
in keyword, contravariance reverses the standard assignment compatibility of generic types. If TypeB inherits from TypeA, contravariance enables an implicit reference conversion from IGeneric<TypeA> to IGeneric<TypeB>.
Syntax and Declaration
Contravariance is declared by placing thein contextual keyword before the type parameter in the angle brackets of an interface or delegate declaration.
Type System Mechanics
In a standard, invariant generic type,IGeneric<Base> and IGeneric<Derived> share no inheritance relationship, regardless of the relationship between Base and Derived. Contravariance alters the compiler’s type-checking rules to permit safe downward assignments.
Compiler Constraints and Rules
To guarantee type safety, the C# compiler enforces strict structural rules on how a contravariant type parameter (in T) can be utilized within the interface or delegate definition:
- Input Positions Only: The type parameter
Tcan only be used in contravariant (input) positions. It may appear as a method parameter type or a write-only property type.
- Prohibited Output Positions: The type parameter
Tcannot be used as a method return type, a read-only property, or a read-write property. Returning a contravariant type violates type safety because the caller expects a specific derived type, but the underlying implementation might return a base type.
- Reference Types Only: Variance in C# is implemented via reference conversions in the CLR. Therefore, contravariance only supports reference types. It does not apply to value types (structs or primitives) because value types do not share the same memory representation.
- Interfaces and Delegates Only: The
inmodifier can only be applied to generic interfaces and generic delegates. It cannot be applied to generic classes, structs, or records.
Master C# with Deep Grasping Methodology!Learn More





