How do I handle events in C#

In C#, events are a key part of the language's event-driven programming model. An event allows a class or object to notify other classes or objects when something of interest occurs. This capability is typically used for user interface actions, such as button clicks or mouse movements, but can be applied in various scenarios.

To define an event in C#, you typically follow these steps:

  1. Declare a delegate that defines the signature of the event handler method.
  2. Declare the event using the delegate type.
  3. Raise the event using the '?.Invoke()' method.

Here's an example demonstrating how to handle events:

// Delegate declaration public delegate void Notify(); // Class that publishes the event public class Publisher { public event Notify ProcessCompleted; public void StartProcess() { // Process code here... // Raise the event ProcessCompleted?.Invoke(); } } // Subscriber class public class Subscriber { public void Subscribe(Publisher publisher) { publisher.ProcessCompleted += OnProcessCompleted; } private void OnProcessCompleted() { Console.WriteLine("Process completed!"); } } // Example usage class Program { static void Main(string[] args) { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); subscriber.Subscribe(publisher); publisher.StartProcess(); // This will trigger the event } }

C# events event handling event-driven programming delegates subscribers