Introduction
The EventHandler delegate pattern helps programs respond to actions like button clicks or messages by running specific code when those actions happen.
public delegate void EventHandler(object sender, EventArgs e); // Usage example: public event EventHandler MyEvent; // To raise the event: MyEvent?.Invoke(this, EventArgs.Empty);
public event EventHandler Clicked; // Raising the event Clicked?.Invoke(this, EventArgs.Empty);
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" });
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(); } }
EventHandler delegate in C#?EventHandler delegate specifically defines the signature for methods that handle events.EventHandler delegate in a class?event followed by the delegate type and event name.public event EventHandler MyEvent; matches the correct pattern.using System;
class Program {
public static event EventHandler OnAction;
static void Main() {
OnAction += (sender, e) => Console.WriteLine("Action happened!");
OnAction?.Invoke(null, EventArgs.Empty);
}
}OnAction.?.Invoke, so it calls the subscribed method, printing the message.public class Button {
public event EventHandler Click;
public void SimulateClick() {
Click(null, EventArgs.Empty);
}
}Click?.Invoke(this, EventArgs.Empty); to safely invoke the event.EventHandler pattern?EventArgs with needed properties.EventHandler<YourArgs> to pass the custom data safely.Pass the test and this pattern moves unknown