← Back to C# Course | Chapter 11: Generics | Lesson 5 of 6

Covariance और Contravariance

Covariance और contravariance यह नियम हैं कि कब एक type का container किसी संबंधित type के container की जगह ले सकता है, जैसे apples की एक basket fruit की basket गिनी जाए। वे तय करते हैं कि यह swap कब सुरक्षित है।
Syntax
csharp
interface IProducer<out T> { T Get(); }       // covariance: out
interface IConsumer<in T> { void Use(T item); }   // contravariance: in

IEnumerable<object> items = new List<string>();

Covariance and Contravariance

Covariance (out T) किसी ज़्यादा derived type वाले generic interface को वहां उपयोग होने देता है जहां एक कम derived type की उम्मीद हो, जैसे IEnumerable<string> को IEnumerable<object> की तरह treat करना।

Contravariance (in T) input positions के लिए विपरीत दिशा में काम करता है, जैसे delegates। ये annotations सिर्फ interfaces और delegates पर लागू होते हैं, classes पर नहीं, और सिर्फ reference types के लिए मायने रखते हैं।

Note: IEnumerable<T> covariant है, यही वजह है कि आप एक List<string> को कहीं भी पास कर सकते हैं जहां IEnumerable<object> की उम्मीद हो।

उदाहरण: Covariance and Contravariance

markup
using System;
using System.Collections.Generic;

class Program
{
    static void PrintAll(IEnumerable<object> items)
    {
        foreach (object item in items)
        {
            Console.WriteLine(item);
        }
    }

    static void Main(string[] args)
    {
        List<string> names = new List<string> { "Ana", "Bo" };
        PrintAll(names); // covariance: IEnumerable<string> used as IEnumerable<object>
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. List<T> के साथ covariance उपयोग करने की कोशिश करना, जो invariant है; सिर्फ IEnumerable<out T> जैसे interfaces इसकी अनुमति देते हैं।
  2. in (contravariance) को out (covariance) के साथ confuse करना।
  3. किसी parameter position पर out T उपयोग करना, जिसकी अनुमति नहीं है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.