0
0
C Sharp (C#)programming~5 mins

Contravariance with in keyword in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Contravariance lets you use a more general type than originally specified. It helps when you want to pass a less specific type safely.

When you want to assign a delegate or interface that accepts a derived type to one that expects a base type.
When you want to write methods that can accept parameters of a more general type than originally declared.
When working with generic interfaces or delegates that consume input parameters and you want flexibility in type assignments.
Syntax
C Sharp (C#)
interface IExample<in T> {
    void DoSomething(T item);
}

The in keyword before the generic type parameter means contravariance.

Contravariant types can only be used as input (method parameters), not as output (return types).

Examples
This interface uses in to allow contravariance on T.
C Sharp (C#)
interface IConsumer<in T> {
    void Consume(T item);
}
This assignment is allowed because string is more specific than object, and in enables contravariance.
C Sharp (C#)
IConsumer<object> consumer = new Consumer<string>();
Sample Program

Here, IConsumer<in T> allows assigning IConsumer<object> (implemented by ObjectConsumer) to IConsumer<string> because of contravariance. The method Consume accepts an object, but the variable is typed as IConsumer<string>.

C Sharp (C#)
using System;

interface IConsumer<in T>
{
    void Consume(T item);
}

class ObjectConsumer : IConsumer<object>
{
    public void Consume(object item)
    {
        Console.WriteLine($"Consumed object: {item}");
    }
}

class Program
{
    static void Main()
    {
        IConsumer<string> consumer = new ObjectConsumer();
        consumer.Consume("Hello World");
    }
}
OutputSuccess
Important Notes

Contravariance only works with input parameters, not return types.

You cannot use the contravariant type parameter to return values from methods.

Contravariance helps make your code more flexible and reusable.

Summary

Use in keyword to declare contravariant generic type parameters.

Contravariant types can accept more general types safely.

It applies only to input positions like method parameters.