In the world of programming, especially when dealing with object-oriented systems, handling events and notifications is a fundamental concept. Events allow objects to communicate with each other by sending signals that can trigger specific actions or behaviors. In this tutorial, we will explore how to handle events and notifications in C#, providing both theoretical understanding and practical examples.
An event in C# is a mechanism for communication between objects. It allows an object (the publisher) to notify one or more other objects (subscribers) that something has happened. Events are based on delegates, which we will discuss in detail later.
Let's walk through a practical example to understand how events work in C#.
Suppose we have a Button class that raises an event when clicked, and a Logger class that subscribes to this event to log the click.
public delegate void ClickEventHandler();
public class Button
{
public event ClickEventHandler OnClick;
public void Click()
{
Console.WriteLine("Button was clicked.");
OnClick?.Invoke();
}
}
In this example, we define a `ClickEventHandler` delegate that represents the signature of methods that can handle the click event. The `Button` class has an event `OnClick` based on this delegate.
#### Step 2: Create the Subscriber
```csharp
public class Logger
{
public void LogClick()
{
Console.WriteLine("Logging button click.");
}
}
The `Logger` class has a method `LogClick` that matches the signature of the `ClickEventHandler` delegate. This method will be used to handle the click event.
#### Step 3: Subscribe and Raise the Event
```csharp
public class Program
{
public static void Main()
{
Button button = new Button();
Logger logger = new Logger();
// Subscribe to the event
button.OnClick += logger.LogClick;
// Simulate a button click
button.Click();
// Unsubscribe from the event
button.OnClick -= logger.LogClick;
}
}
In this example, we create instances of `Button` and `Logger`. We subscribe the `LogClick` method to the `OnClick` event of the `Button` instance. When the `Click` method is called on the `Button`, it raises the `OnClick` event, which in turn invokes the `LogClick` method.
### Example 2: Event with Parameters
Events can also carry data using parameters. Let's modify our previous example to include a message parameter when the button is clicked.
#### Step 1: Modify the Delegate and Event
```csharp
public delegate void ClickEventHandler(string message);
public class Button
{
public event ClickEventHandler OnClick;
public void Click(string message)
{
Console.WriteLine("Button was clicked.");
OnClick?.Invoke(message);
}
}
Here, we modify the ClickEventHandler delegate to accept a string parameter. The Click method of the Button class now takes a message and passes it to the event.
public class Logger
{
public void LogClick(string message)
{
Console.WriteLine($"Logging button click with message: {message}");
}
}
The LogClick method of the Logger class now accepts a string parameter to handle the message passed by the event.
public class Program
{
public static void Main()
{
Button button = new Button();
Logger logger = new Logger();
// Subscribe to the event
button.OnClick += logger.LogClick;
// Simulate a button click with a message
button.Click("Hello, World!");
// Unsubscribe from the event
button.OnClick -= logger.LogClick;
}
}
In this example, when the Click method is called on the Button instance with a message, it raises the OnClick event and passes the message to all subscribed methods. The LogClick method of the Logger class logs the message.
After mastering events in C#, you should explore "Delegates in C#" to gain a deeper understanding of how delegates work under the hood and how they relate to events. Delegates are a powerful feature of C# that enable flexible and dynamic programming techniques.
By following this tutorial, you have learned how to declare, subscribe, raise, and unsubscribe from events in C#. You should now be able to implement event-driven programming in your applications, allowing for more interactive and responsive designs.