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

Generic Interfaces क्या हैं

एक generic interface एक fill-in-the-type-blank वाली promise list है, जैसे एक job जो cook या driver के लिए हो सकती है। अलग-अलग classes इसे अलग types के साथ उपयोग कर सकती हैं।

In this page:

  1. Generic Interfaces
Syntax
csharp
interface IInterfaceName<T>
{
    void Add(T item);
    T Get();
}

class ClassName<T> : IInterfaceName<T>
{
    // implement Add and Get
}

Generic Interfaces

Interfaces भी generic हो सकते हैं, जैसे built-in IComparable<T> या IEnumerable<T>, किसी contract को एक class की तरह type से parameterized होने देते हुए।

IContainer<T> implement करने वाली class implementation के समय चुनी एक specific type T के साथ काम करने के लिए commit करती है। यह interface contracts को object पर निर्भर रहने के बजाय सटीक और type-safe रखता है।

Note: manual casting से बचने के लिए IEnumerable जैसे non-generic ancestors से IEnumerable<T> जैसे generic interfaces को प्राथमिकता दें।

उदाहरण: Generic Interfaces

markup
using System;

interface IContainer<T>
{
    void Add(T item);
    T GetFirst();
}

class SingleItemContainer<T> : IContainer<T>
{
    private T item;

    public void Add(T item)
    {
        this.item = item;
    }

    public T GetFirst()
    {
        return item;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IContainer<string> container = new SingleItemContainer<string>();
        container.Add("first item");
        Console.WriteLine(container.GetFirst());
    }
}
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. बिना type argument के किसी generic interface को implement करना, जैसे class Box : IContainer, जो compile नहीं होता क्योंकि IContainer<T> को अपना T चाहिए।
  2. IContainer<int> और IContainer<string> को एक ही type मानना, जबकि हर closed generic type एक अलग type है और वे interchangeable नहीं हैं।
  3. यह मान लेना कि किसी IContainer<Dog> का उपयोग वहां किया जा सकता है जहां एक IContainer<Animal> की उम्मीद हो, जिसकी अनुमति नहीं है जब तक interface variance (out/in) के साथ declared न हो।
🔒

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.