"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Doesn't Covariance Work with Value Types in C#?

Why Doesn't Covariance Work with Value Types in C#?

Posted on 2025-03-25
Browse:598

Why Doesn't Covariance Work with Value Types in C#?

C# Covariance and Contravariance: Value Type Restrictions

The IEnumerable interface in C# exhibits covariance, allowing assignment of derived type references to base type references. However, this doesn't apply to value types. Assigning IEnumerable to IEnumerable results in a compilation error.

This limitation stems from boxing and unboxing. Boxing converts a value type into a reference type (object), while unboxing reverses this. IEnumerable's type parameter T only works with reference types. Assigning an IEnumerable of a value type to an IEnumerable necessitates boxing, which isn't implicitly supported for value types.

Covariance and contravariance rely on consistent value representation across conversions. Value types, however, don't maintain this consistency. Boxing changes their representation, potentially leading to identity loss and instability, violating the principles of covariant and contravariant assignments.

Eric Lippert's writings on representation and identity highlight that these conversions demand identity preservation. Because value types' boxing process breaks this preservation, they are incompatible with covariance and contravariance.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3