0
0
C Sharp (C#)programming~5 mins

EventHandler delegate pattern in C Sharp (C#)

Choose your learning style9 modes available
Introduction
The EventHandler delegate pattern helps programs respond to actions like button clicks or messages by running specific code when those actions happen.
When you want your program to do something after a user clicks a button.
When you need to notify parts of your program that something important happened.
When you want to keep your code organized by separating the action from the response.
When building interactive applications like games or forms.
When you want multiple parts of your program to react to the same event.
Syntax
C Sharp (C#)
public delegate void EventHandler(object sender, EventArgs e);

// Usage example:
public event EventHandler MyEvent;

// To raise the event:
MyEvent?.Invoke(this, EventArgs.Empty);
The EventHandler delegate always has two parameters: the sender (who raised the event) and EventArgs (extra info about the event).
You can create your own EventArgs class if you want to send more details with the event.
Examples
This example shows a simple event named Clicked using the EventHandler delegate.
C Sharp (C#)
public event EventHandler Clicked;

// Raising the event
Clicked?.Invoke(this, EventArgs.Empty);
Here we use a custom EventArgs class to send a message with the event.
C Sharp (C#)
public class MyEventArgs : EventArgs {
    public string Message { get; set; }
}

public event EventHandler<MyEventArgs> MessageReceived;

// Raising the event with custom data
MessageReceived?.Invoke(this, new MyEventArgs { Message = "Hello" });
Sample Program
This program shows how to declare an event with EventHandler, subscribe to it, and raise it. When DoSomething runs, it triggers the event and the subscribed code runs.
C Sharp (C#)
using System;

class Program {
    // Declare an event using EventHandler
    public event EventHandler SomethingHappened;

    public void DoSomething() {
        Console.WriteLine("Doing something important...");
        // Raise the event
        SomethingHappened?.Invoke(this, EventArgs.Empty);
    }

    static void Main() {
        Program p = new Program();

        // Subscribe to the event with a method
        p.SomethingHappened += (sender, e) => {
            Console.WriteLine("Event received! Responding now.");
        };

        p.DoSomething();
    }
}
OutputSuccess
Important Notes
Always check if the event is not null before raising it using the ?. operator to avoid errors.
EventHandler is a built-in delegate type in C# designed for events with no extra data.
Use custom EventArgs classes when you want to send more information with your event.
Summary
EventHandler delegate pattern helps your program react to actions or changes.
Events use EventHandler to connect the action with the response code.
You can send extra info with events by creating custom EventArgs classes.