Generic Methods क्या हैं
एक generic method एक helper है जो कई तरह की चीज़ों के साथ काम करता है, जैसे एक scoop जो sand या snow दोनों उठा सके। आप इसे एक बार लिखते हैं, और यह आपकी दी गई किसी भी type के अनुकूल हो जाता है।
In this page:
Syntax
static ReturnType MethodName<T>(T parameter)
{
// body
}
MethodName<type>(argument); // type can often be inferred: MethodName(argument);
Generic Methods
कोई method खुद अपने आप generic हो सकता है, किसी non-generic class के अंदर भी, parameter list से पहले angle brackets में अपना खुद का type parameter declare करके।
Compiler आमतौर पर आपके पास किए arguments से type argument infer कर लेता है, इसलिए आपको शायद ही कभी इसे explicitly specify करने की ज़रूरत पड़े। यह एक single method को कई types में सही से काम करने देता है।
Note:
अगर type inference इसे पता नहीं लगा सके तो आप किसी generic method को explicitly
Method<int>(...) से call कर सकते हैं।उदाहरण: Generic Methods
using System;
class Program
{
static void PrintTwice<T>(T value)
{
Console.WriteLine(value);
Console.WriteLine(value);
}
static void Main(string[] args)
{
PrintTwice(5);
PrintTwice("hi");
PrintTwice(3.14);
}
}
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
Tकी किसी value परa + bयाa > bजैसे operators उपयोग करना, जो compile नहीं होता क्योंकि एक unconstrainedTकोई भी type हो सकता है; एक constraint जोड़ें याIComparable<T>उपयोग करें। <int>specify किए बिनाCreate<T>()जैसे किसी generic method को call करना, जब compilerTinfer नहीं कर सकता क्योंकि कोई argument इसे उपयोग नहीं करता।where T : new()के बिना किसी generic method के अंदरnew T()लिखना, जो एक compile error है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: