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 event) 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.

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

Code:

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.

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