Generic Classes क्या हैं
एक generic class एक container है जो आपकी चुनी किसी भी type को रख सकता है, जैसे 'for shoes' या 'for toys' नाम का box। आप इसे एक बार लिखते हैं और सुरक्षित रूप से कई types के साथ उपयोग करते हैं।
In this page:
Syntax
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- type argument भूल जाना, जैसे
Box<T>के लिएBox b = new Box();, जो एक compile error है। - यह मान लेना कि
Tबिना किसी constraint के+जैसे operators support करता है, जो एक compile error है। new()constraint के बिनाnew T()उपयोग करना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: