C# Events

C# Code Snippets Events
Share:

About

In this code snippet, we will take a look at events in C#.

A class(subscriber class) can subscribe to an event of another class(publisher class). The publisher class notifies the subscriber class every time the event occurs. This works by using delegates. The subscriber will pass its delegate to the publisher class to “make a subscription” to its event. When the event occurs the publisher will call the delegate(callback method) that was provided to it by the subscriber when it “subscribed” to the event. This is how (for example button press events) events work in .NET. This principle of operation is also called the observer pattern.

See this post if you want to know how to send event arguments(pass data with the event) along with your events.

Important Notes:

Unsubsribing: The subscriber classes should always unsubscribe from the publisher class before being disposed of to prevent memory leaks. This can be done by using -= (see in the example below). I would recommend you do this in the destructor of your subscriber class.

Lambda Expression: If you subscribe to an event using an anonymous function(lambda expression) you can’t easily unsubscribe. So only use anonymous functions to subscribe to events when you know you won’t need to unsubscribe for the entire lifecycle of your program.

Let’s have a look at the code below to see how to use events.

Code:

using System;

namespace Events
{
    class Program
    {
        static void Main(string[] args)
        {
            //Make new switch.
            Switch sw = new Switch();
            //Make new light and add the event.
            Light light = new Light(sw);
            
            //Toggle the switch. 
            sw.lightSwitchToggle();

            Console.ReadLine();
        }
    }

    class Switch
    {
        //Make a delegate.
        public delegate void ToggleDelegate();

        //An event is basically a restricted delegate. 
        //Other classes can only subscribe or unsubscribe from the event and can't invoke or assign it as if it was a delegate. 
        public event ToggleDelegate toggleEvent;

        //When this method is called the event will be invoked.
        public  void lightSwitchToggle()
        {
            toggleEvent();
        }
    }

    class Light
    {
        Switch sw;
        public Light(Switch SW)
        {
            //Give Light a reference to the instance of Switch.
            this.sw = SW;

            //Add/chain a new method on the event.  
            this.sw.toggleEvent += turnOnTheLight();

            //Remove event if desired.
            //sw.toggleEvent -= turnOnTheLight(); 
        }

        private void turnOnTheLight()
        {       
            Console.WriteLine("The light was toggled.");
        }
    }
}

Resulting output:

Share:

Comments

  1. Thanks – your example was a useful to me. Just one thing though;

    If you subscribe to an event using an anonymous Lambda expression;
    this.sw.toggleEvent += () => turnOnTheLight();

    Then you can’t uncomment this line below to unsubscribe from it;
    this.sw.toggleEvent -= () => turnOnTheLight();

    That may not be an issue but in some situations it can lead to memory leaks as the subscriber holds a pointer to the publisher preventing it being garbage collected, even if the publisher has has gone out of scope.

    There’s some info on this at;
    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events

    1. I haven’t considered a memory leak being a possible problem as a result of using the lambda expression. Thank you for pointing this out. I will update the post.

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger