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

Generic Classes क्या हैं

एक generic class एक container है जो आपकी चुनी किसी भी type को रख सकता है, जैसे 'for shoes' या 'for toys' नाम का box। आप इसे एक बार लिखते हैं और सुरक्षित रूप से कई types के साथ उपयोग करते हैं।

In this page:

  1. Generic Classes
Syntax
csharp
class ClassName<T>
{
    private T value;
    public void Set(T value) { this.value = value; }
    public T Get() { return value; }
}

ClassName<type> variable = new ClassName<type>();

Generic Classes

एक generic class एक type parameter उपयोग करती है, जैसे Box<T>, ताकि वही class definition किसी भी type के साथ काम करे जबकि पूरी तरह type-safe रहे।

class instantiate होने पर असली type दी जाती है, जैसे Box<int> या Box<string>। यह आपकी ज़रूरत वाली हर type के लिए एक जैसी class दोहराने से बचाता है।

Note: Generic type parameters conventionally T नाम लेते हैं, या कई parameters के लिए TKey/TValue जैसा कुछ descriptive।

उदाहरण: Generic Classes

markup
using System;

class Box<T>
{
    private T value;

    public void Set(T value)
    {
        this.value = value;
    }

    public T Get()
    {
        return value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Box<int> intBox = new Box<int>();
        intBox.Set(42);
        Console.WriteLine(intBox.Get());

        Box<string> strBox = new Box<string>();
        strBox.Set("hello");
        Console.WriteLine(strBox.Get());
    }
}
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 भूल जाना, जैसे Box<T> के लिए Box b = new Box();, जो एक compile error है।
  2. यह मान लेना कि T बिना किसी constraint के + जैसे operators support करता है, जो एक compile error है।
  3. new() constraint के बिना new 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.