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

Generic Methods क्या हैं

एक generic method एक helper है जो कई तरह की चीज़ों के साथ काम करता है, जैसे एक scoop जो sand या snow दोनों उठा सके। आप इसे एक बार लिखते हैं, और यह आपकी दी गई किसी भी type के अनुकूल हो जाता है।

In this page:

  1. Generic Methods
Syntax
csharp
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

markup
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);
    }
}
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 T की किसी value पर a + b या a > b जैसे operators उपयोग करना, जो compile नहीं होता क्योंकि एक unconstrained T कोई भी type हो सकता है; एक constraint जोड़ें या IComparable<T> उपयोग करें।
  2. <int> specify किए बिना Create<T>() जैसे किसी generic method को call करना, जब compiler T infer नहीं कर सकता क्योंकि कोई argument इसे उपयोग नहीं करता।
  3. 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:

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.