What is EventHandler in C#: Simple Explanation and Example
EventHandler in C# is a predefined delegate type used to handle events. It represents a method that will be called when an event occurs, typically taking an object sender and EventArgs as parameters.How It Works
Think of EventHandler as a messenger that delivers a signal when something happens, like a button being clicked. It connects the event source (like the button) to the code that responds to that event (the event handler method).
When the event occurs, the EventHandler calls the method you wrote to react to it. It always sends two pieces of information: who sent the event (the sender) and details about the event (event arguments).
This setup helps keep your program organized by separating the event trigger from the response, making your code easier to manage and understand.
Example
This example shows how to use EventHandler to respond when a simple event is triggered.
using System; class Program { // Declare an event using EventHandler delegate public static event EventHandler SomethingHappened; static void Main() { // Subscribe a method to the event SomethingHappened += OnSomethingHappened; // Trigger the event OnEventTriggered(); } // Method to raise the event static void OnEventTriggered() { // Check if there are subscribers SomethingHappened?.Invoke(null, EventArgs.Empty); } // Event handler method static void OnSomethingHappened(object sender, EventArgs e) { Console.WriteLine("The event was triggered and handled."); } }
When to Use
Use EventHandler when you want to notify other parts of your program that something important happened, like a user action or a system change.
Common real-world uses include button clicks in user interfaces, completion of tasks, or changes in data. It helps your program react dynamically without tightly coupling the event source and the response.
Key Points
- EventHandler is a built-in delegate for events with no special data.
- It always takes
object senderandEventArgs eas parameters. - It helps separate event triggers from event responses.
- Use it to create clean, maintainable event-driven code.
Key Takeaways
EventHandler is a delegate type used to handle events with standard parameters.EventHandler to keep your code organized and responsive to actions.