Under the Hood

Co- and contravariance for interface and delegate types has been supported by the CLR since the introduction of generics back in the .NET 2.0 days. And being supported at the runtime and IL level makes it amenable for cross-language support once more. Given the following two types, let’s take a look under the hood:

interface IReadOnly<out T> {    T Give();}interface IWriteOnly<in T> {    void Take(T input);}

At the assembly-level as shown in Figure 15.39, covariance is indicated with a + symbol in front of a type parameter, while contravariance is denoted with -.

Image

FIGURE 15.39 Co- and contravariance behind the scenes.

Different ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.