← Back to C# Course | Chapter 12: Delegates & Events | Lesson 1 of 6

Delegates क्या हैं

एक delegate एक variable है जो एक method रखता है, जैसे एक phone contact जिसे आप बाद में call कर सकते हैं। यह आपको actions को objects की तरह पास करने देता है।

In this page:

  1. Delegates
Syntax
csharp
delegate ReturnType DelegateName(type parameter);

DelegateName variable = MethodName;
ReturnType result = variable(argument);

Delegates

एक delegate किसी method का एक type-safe reference है, आपको methods को values की तरह पास करने देते हुए — parameters, return values के रूप में, या variables में store करते हुए।

आप एक delegate type declare करते हैं जो describe करती है कि यह किस method signature को point कर सकता है, फिर कोई भी matching method इसे assign करते हैं। delegate को call करना चाहे यह वर्तमान में जो भी method reference करता हो उसे invoke करता है।

Note: Delegates वह नींव हैं जिन पर lambda expressions, Func<>/Action<>, और events सब बने हैं।

उदाहरण: Delegates

markup
using System;

delegate int Operation(int a, int b);

class Program
{
    static int Add(int a, int b) => a + b;
    static int Multiply(int a, int b) => a * b;

    static void Main(string[] args)
    {
        Operation op = Add;
        Console.WriteLine(op(3, 4));

        op = Multiply;
        Console.WriteLine(op(3, 4));
    }
}
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. किसी null delegate को सीधे invoke करना, जो NullReferenceException फेंकता है; ?.Invoke का उपयोग करें।
  2. किसी ऐसे method को assign करना जिसका signature delegate type से मेल न खाए, जो एक compile error है।
  3. Method() से method को call करने को Method से इसे पास करने के साथ confuse करना।
🔒

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.