Events In C#
Published: 2022-10-04 21:24:05

**Events** enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

In a typical C# Windows Forms or Web application, you subscribe to events raised by controls such as buttons and list boxes. You can use the Visual C# integrated development environment (IDE) to browse the events that a control publishes and select the ones that you want to handle. The IDE provides an easy way to automatically add an empty event handler method and the code to subscribe to the event.

## Events Overview

Events have the following properties:
• The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
• An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
• Events that have no subscribers are never raised.
• Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
• When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, we use Calling Synchronous Methods Asynchronously.
• In the .NET class library, events are based on the EventHandler delegate and the EventArgs base class.

## How to subscribe to and unsubscribe from events

**_To subscribe to events programmatically_**

1. Define an event handler method whose signature matches the delegate signature for the event. For example, if the event is based on the EventHandler delegate type, the following code represents the method stub:

_void HandleCustomEvent(object sender, CustomEventArgs a)  
{  
   // Do something useful here.  
}_

Use the addition assignment operator (+=) to attach an event handler to the event. In the following example, assume that an object named publisher has an event named RaiseCustomEvent. Note that the subscriber class needs a reference to the publisher class in order to subscribe to its events.

_publisher.RaiseCustomEvent += HandleCustomEvent;_

**_To subscribe to events by using an anonymous function_**

If you don't have to unsubscribe from an event later, you can use the addition assignment operator (+=) to attach an anonymous function as an event handler. In the following example, assume that an object named publisher has an event named RaiseCustomEvent and that a CustomEventArgs class has also been defined to carry some kind of specialized event information. Note that the subscriber class needs a reference to publisher in order to subscribe to its events

_publisher.RaiseCustomEvent += (object o, CustomEventArgs e) =>
{  
  string s = o.ToString() + " " + e.ToString();  
  Console.WriteLine(s);  
};_

You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event. We recommend that you don't use anonymous functions to subscribe to events if you have to unsubscribe from the event at some later point in your code.

## Unsubscribing


To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object.

To unsubscribe from an event
• Use the subtraction assignment operator (-=) to unsubscribe from an event:
• _publisher.RaiseCustomEvent -= HandleCustomEvent;_

When all subscribers have unsubscribed from an event, the event instance in the publisher class is set to null.

Events are, like delegates, a late binding mechanism. In fact, events are built on the language support for delegates.
Events are a way for an object to broadcast (to all interested components in the system) that something has happened. Any other component can subscribe to the event, and be notified when an event is raised.

You've probably used events in some of your programming. Many graphical systems have an event model to report user interaction. These events would report mouse movement, button presses and similar interactions. That's one of the most common, but certainly not the only scenario where events are used.

You can define events that should be raised for your classes. One important consideration when working with events is that there may not be any object registered for a particular event. You must write your code so that it does not raise events when no listeners are configured.

Subscribing to an event also creates a coupling between two objects (the event source, and the event sink). You need to ensure that the event sink unsubscribes from the event source when no longer interested in events.