.NET Events and Invocation Guide
Events in .NET provide a way to enable communication between objects, following the publisher-subscriber pattern. This guide covers defining, subscribing, and invoking events in C#.
Defining an Event
An event in .NET is defined using the event
keyword. It is typically based on a delegate that determines the signature of the event handler.
Example:
public class EventPublisher
{
// Define a delegate for the event
public delegate void SampleEventHandler(object sender, EventArgs e);
// Define the event based on the delegate
public event SampleEventHandler SampleEvent;
// Method to invoke the event
protected virtual void OnSampleEvent()
{
SampleEvent?.Invoke(this, EventArgs.Empty);
}
}
Subscribing to an Event
A method can subscribe to an event using the +=
operator.
Example:
public class EventSubscriber
{
public void Subscribe(EventPublisher publisher)
{
publisher.SampleEvent += HandleSampleEvent;
}
private void HandleSampleEvent(object sender, EventArgs e)
{
Console.WriteLine("Sample event triggered!");
}
}
Unsubscribing from an Event
To prevent memory leaks, always unsubscribe from events when they are no longer needed using the -=
operator.
Example:
public void Unsubscribe(EventPublisher publisher)
{
publisher.SampleEvent -= HandleSampleEvent;
}
Invoking an Event
An event is invoked using the Invoke
method, ensuring it is not null
.
Example:
protected virtual void OnSampleEvent()
{
SampleEvent?.Invoke(this, EventArgs.Empty);
}
Using EventHandler<T>
Instead of defining a custom delegate, it is recommended to use the built-in EventHandler
and EventHandler<T>
for event handling.
Example:
public class EventPublisher
{
public event EventHandler<MyEventArgs> CustomEvent;
protected virtual void OnCustomEvent(string message)
{
CustomEvent?.Invoke(this, new MyEventArgs(message));
}
}
public class MyEventArgs : EventArgs
{
public string Message { get; }
public MyEventArgs(string message)
{
Message = message;
}
}
Anonymous Methods and Lambda Expressions
Events can also be handled using anonymous methods or lambda expressions.
Example:
publisher.SampleEvent += (sender, e) => Console.WriteLine("Event triggered via lambda!");
Summary
Action | Code Example |
---|---|
Define an event | public event EventHandler SampleEvent; |
Subscribe to event | publisher.SampleEvent += HandlerMethod; |
Unsubscribe event | publisher.SampleEvent -= HandlerMethod; |
Invoke an event | SampleEvent?.Invoke(this, EventArgs.Empty); |
By following this guide, you can effectively use events in .NET applications for better modularity and decoupling between components.