Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Events in C# Programming

Introduction

Events are a way for objects to communicate with each other in a loosely coupled way. In C#, events are based on delegates and provide a way for a class to notify other classes or objects when something of interest occurs. This tutorial will cover the basics of events in C#, how to declare, subscribe, and raise events.

What is an Event?

An event is a message sent by an object to signal the occurrence of an action. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Declaring an Event

To declare an event, you need to define a delegate type and then declare an instance of that delegate type with the event keyword.

public delegate void Notify(); // Delegate type
public class ProcessBusinessLogic
{
    public event Notify ProcessCompleted; // Event declaration
}

Subscribing to an Event

To subscribe to an event, you need to create a method that matches the delegate signature and then use the += operator to attach the event handler to the event.

public class ProcessBusinessLogic
{
    public event Notify ProcessCompleted; // Event declaration
    public void StartProcess()
    {
        // Some process code here
        OnProcessCompleted(); // Raise the event
    }
    protected virtual void OnProcessCompleted()
    {
        if (ProcessCompleted != null)
            ProcessCompleted.Invoke();
    }
}

public class Program
{
    static void Main(string[] args)
    {
        ProcessBusinessLogic bl = new ProcessBusinessLogic();
        bl.ProcessCompleted += bl_ProcessCompleted;
        bl.StartProcess();
    }
    public static void bl_ProcessCompleted()
    {
        Console.WriteLine("Process Completed!");
    }
}

Raising an Event

To raise an event, you invoke the event delegate. It is a good practice to check if the event is null (i.e., if there are any subscribers) before raising it. This can be done using the null-conditional operator ?. in modern C#.

protected virtual void OnProcessCompleted()
{
    ProcessCompleted?.Invoke();
}

Event Handler

An event handler is a method that is called when an event is raised. The event handler must match the signature of the delegate used for the event. Event handlers can also be lambda expressions or anonymous methods.

public static void bl_ProcessCompleted()
{
    Console.WriteLine("Process Completed!");
}

Complete Example

Here is a complete example that demonstrates declaring, subscribing, and raising an event in C#.

using System;

public delegate void Notify();

public class ProcessBusinessLogic
{
    public event Notify ProcessCompleted;

    public void StartProcess()
    {
        Console.WriteLine("Process Started!");
        // Some process code here
        OnProcessCompleted();
    }

    protected virtual void OnProcessCompleted()
    {
        ProcessCompleted?.Invoke();
    }
}

public class Program
{
    static void Main(string[] args)
    {
        ProcessBusinessLogic bl = new ProcessBusinessLogic();
        bl.ProcessCompleted += Bl_ProcessCompleted;
        bl.StartProcess();
    }

    private static void Bl_ProcessCompleted()
    {
        Console.WriteLine("Process Completed!");
    }
}

Conclusion

Events in C# provide a way for objects to communicate with each other in a loosely coupled manner. By using delegates as the basis for events, C# allows for flexible and powerful event handling mechanisms. This tutorial covered the basics of declaring, subscribing, and raising events. With this knowledge, you can start using events to build more interactive and responsive applications.