C# / C# Delegates, Events, and Lambdas

Implementing Event Handling in C#

Understanding how to handle events is crucial for creating interactive C# applications. This tutorial will walk you through the process of handling events, discussing how to creat…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers delegates, events, and lambda expressions for advanced programming in C#.

Implementing Event Handling in C

1. Introduction

In this tutorial, we will delve into the process of handling events in C#. Event handling is a key aspect of creating interactive C# applications, and understanding this concept is crucial for every developer.

You will learn how to:

  • Define and declare events
  • Create subscribers
  • Respond to events

Prerequisites: Familiarity with C# basics and Object Oriented Programming principles.

2. Step-by-Step Guide

In C#, an event is a way for a class to provide notifications to other classes when something of interest happens. The class that sends (or raises) the event is the publisher and the classes that receive (or handle) the event are the subscribers.

Events

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that make up a Windows Forms or WPF application will have events.

Delegates

Delegates are a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type-safe, and secure.

Event Handlers

Event handlers are methods in the subscriber class that will be executing the event. It must match the signature of the delegate.

3. Code Examples

// declaring the delegate
public delegate void MyEventHandler(string foo);

// declaring the event using the delegate
public event MyEventHandler MyEvent;

// method to raise the event
protected virtual void OnMyEvent(string foo)
{
    MyEvent?.Invoke(foo);
}

In the code snippet above:

  • We first declare a delegate MyEventHandler that takes a string as an argument.
  • We then declare an event MyEvent using this delegate.
  • Then we define a method OnMyEvent that invokes the MyEvent. The ?. operator is used to check if there is any subscriber to the event before invoking it.

Subscribing to an Event

public class Subscriber
{
    public void Subscribe(Publisher pub)
    {
        pub.MyEvent += RespondToEvent; // subscribing to the event
    }

    // event handler
    private void RespondToEvent(string foo)
    {
        Console.WriteLine($"Event received: {foo}");
    }
}

In the code snippet above:

  • We define a Subscriber class with a Subscribe method. This method takes a Publisher object and subscribes to its MyEvent event by assigning an event handler RespondToEvent.
  • The RespondToEvent is defined to handle the event. It simply prints the message received from the event.

4. Summary

In this tutorial, we've covered how to declare and define events in C#, how to subscribe to these events and how to respond when these events are raised. Events are a critical component of interactive applications in C#, allowing different parts of an application to communicate with each other in a loosely coupled way.

For further learning, look into more complex scenarios of event handling, such as handling multiple events, unsubscribing from events, and using built-in delegate types like Func and Action.

5. Practice Exercises

  1. Create a Clock class that raises an event Tick every second.

  2. Create a Reminder class that subscribes to the Clock and prints a reminder every minute.

Solutions

  1. Clock Class
public class Clock
{
    public delegate void SecondPassedHandler(object clock, EventArgs timeInfo);
    public event SecondPassedHandler SecondPassed;

    public void Run()
    {
        while (true)
        {
            Thread.Sleep(1000);
            OnSecondPassed(EventArgs.Empty);
        }
    }

    protected virtual void OnSecondPassed(EventArgs e)
    {
        SecondPassed?.Invoke(this, e);
    }
}
  1. Reminder Class
public class Reminder
{
    public void Subscribe(Clock clock)
    {
        clock.SecondPassed += OnSecondPassed;
    }

    private void OnSecondPassed(object clock, EventArgs timeInfo)
    {
        Console.WriteLine("Reminder: One second has passed");
    }
}

In these examples, a Clock class is created that raises an event every second. A Reminder class is also created that subscribes to the Clock's event and displays a reminder every second.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help