Codectionary / Developer documentation / C#

Understand Generic Variance: in and out

Use producer and consumer contracts to convert compatible generic interfaces and delegates safely.

Read the syntax

Use producer and consumer contracts to convert compatible generic interfaces and delegates safely.

A produced string is safely usable as object.

What it is and why to use it

A producer of strings can be used where a producer of objects is expected, because every produced string is an object. A consumer of any object can handle strings too. Covariance and contravariance express these safe directions for generic interface and delegate parameters. They do not make ordinary mutable generic classes such as List<T> covariant.

How it works

out marks a covariant parameter used in output-compatible positions; in marks a contravariant parameter used in input-compatible positions. Variance conversions apply to reference types. IEnumerable<string> can be viewed as IEnumerable<object>, but IEnumerable<int> does not acquire that conversion because int is a value type. A contract’s member signatures must satisfy the compiler’s variance rules.

Common mistakes and limitations

Do not assume that assignability between element types implies assignability between every generic type. A writable List<object> view of List<string> would allow inserting a non-string, which explains why that conversion is unsafe. Use read-oriented interfaces when that is the intended contract.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

interface ISource<out T> { T Read(); }
interface ISink<in T> { void Write(T value); }

Examples

View a string producer as an object producer

Use a covariant interface without copying or changing the underlying object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

ISource<string> words = new WordSource();
ISource<object> objects = words;
Console.WriteLine(objects.Read());
interface ISource<out T> { T Read(); }
class WordSource : ISource<string> { public string Read() => "PHP"; }
  1. ISource only returns T, so its type parameter can be covariant.
  2. A produced string is safely usable as object.
  3. The conversion changes the reference’s contract, not the stored object or its returned value.
  4. Expected output: PHP
  5. Think in terms of values flowing out of or into a contract.

Use a broad consumer for a narrower input

Assign a consumer of objects where a string consumer is needed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

ISink<object> logger = new ObjectSink();
ISink<string> textLogger = logger;
textLogger.Write("Lesson saved");
interface ISink<in T> { void Write(T value); }
class ObjectSink : ISink<object> {
    public void Write(object value) => Console.WriteLine(value);
}
  1. The in parameter is consumed by Write rather than returned.
  2. A consumer that accepts any object can safely accept a string.
  3. The direction is intentionally the reverse of the producer example. This is contravariance, not a conversion that makes the consumer accept fewer values internally.
  4. Expected output: Lesson saved
  5. Think in terms of values flowing out of or into a contract.

Best practices

  • Think in terms of values flowing out of or into a contract.
  • Prefer narrow producer/consumer interfaces over unsafe casts.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading