C#
event handling
delegate
programming tutorial
software development

How can I make my own event in C?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In C#, creating your own events involves understanding and utilizing delegates, event handlers, and the `event` keyword. Events provide a powerful way to allow a class to notify other classes when something of interest occurs. Here is a detailed guide on how to create and use your own events in C#.

Basics of Events in C#

Events in C# are based on delegates, which act like function pointers or callbacks. A delegate is a type that represents references to methods with a particular parameter list and return type.

Steps to Create an Event

  1. Define a Delegate: This specifies the signature of the method(s) that will handle the event.
  2. Declare an Event: This is done using the `event` keyword followed by the delegate. This event can be triggered within the class to notify subscribers.
  3. Write an Event Handler: These are methods that conform to the delegate signature and are executed when the event is raised.
  4. Subscribe to and Unsubscribe from Events: Other classes that need to respond to the event can subscribe to it using the `+=` operator and unsubscribe using the `-=` operator.
  5. Raise the Event: This usually happens in a protected method, allowing the derived classes to safely override and extend the behavior.

Example

Let's create a simple application with a custom event.

  • Delegate Definition: The `ProcessCompletedEventHandler` delegate is defined which will handle the events. It matches the signature and parameters of the methods that will handle the event.
  • Event Declaration: The `event` keyword creates an event named `ProcessCompleted`, which is based on the defined delegate.
  • Raising the Event: The `OnProcessCompleted` method checks for subscribers before raising the event using `?.Invoke()`. This is a pattern to ensure no exceptions are thrown if there are no subscribers.
  • Subscribing to Events: The `Main` method in the `Program` class binds an event handler `Bl_ProcessCompleted` to the `ProcessCompleted` event using `+=`.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.