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

Events क्या हैं

एक event किसी doorbell जैसा है: जब कुछ होता है, सुनने के लिए sign up किए सभी को बता दिया जाता है। Sender को यह जानने की ज़रूरत नहीं कि कौन सुन रहा है।

In this page:

  1. Events
Syntax
csharp
class Publisher
{
    public event Action EventName;

    public void Raise()
    {
        EventName?.Invoke();
    }
}

publisher.EventName += HandlerMethod;   // subscribe

Events

एक event एक delegate-based member है जो publish/subscribe pattern का पालन करता है — कोई class event raise करती है, और कोई भी संख्या में external handlers इस पर react करने के लिए subscribe कर सकते हैं, बिना publisher को यह जाने कि वे कौन हैं।

Subscribers += से attach होते हैं और class इसे एक delegate की तरह invoke करके internally event raise करती है। Events वह तरीका है जिससे UI frameworks और कई libraries code को state changes के बारे में notify करती हैं।

Note: किसी event को सिर्फ अपनी declaring class के अंदर से raise किया जा सकता है, भले ही बाहर का code इसे subscribe कर सके।

उदाहरण: Events

markup
using System;

class Button
{
    public event Action Clicked;

    public void Click()
    {
        Console.WriteLine("Button clicked!");
        Clicked?.Invoke();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Button button = new Button();
        button.Clicked += () => Console.WriteLine("Handler: something happened");

        button.Click();
    }
}
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. subscribers जांचे बिना एक event raise करना, जिससे एक null event throw करता है; Event?.Invoke(...) का उपयोग करें।
  2. इसे declare करने वाली class के बाहर से एक event raise करने की कोशिश करना, जो एक compile error है।
  3. -= से unsubscribe करना भूल जाना, जो objects को जीवित रख सकता है और memory leaks का कारण बन सकता है।
🔒

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.