c#tutorials

Using events in c#

By January 4, 2019No Comments

Introduction

Let’s start with a definition:

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.” (source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/ )

The use of events in c# is pretty straightforward. However, same as every other programming technique, it may take some time for one to get used to and use effectively. Lately I have been revisiting the use of events in c#, trying to make sure that I use them properly in my projects. While doing so, I made a small case study, in the form of a console application, and decided to share it, in case it might help someone else as well.

Example

The following code is a simple, yet fully functional, example of a proper use of events in c#. By “proper” I mean that it is a) functionally correct and b) it conforms to the common standards of the usage of the c# language. I took the time to comment the code in order to explain, the best I could, all of its functionality and turn it into a self – explanatory tutorial. So hopefully, by just reading through the code carefully, one may understand what is going on and why.

Functional description:

In this example, there are 10 number counters, each of which has a different (random) upper bound (MaxNum property). All of them count from zero up until their maximum number. As soon as any of them reaches their maximum, they raise the MaxNumReached event. The notifier object (instance of the Notifier class), which has been subscribed to all of the event publishers, responds to the event by printing useful information to the console.

Console output:

Every time you run the example, the console output will be a bit different (because the maximum number of every number counter is set randomly). However, you should always receive 10  messages (one for each number counter). Here is a sample console output:

“Number Counter 2 has reached its maximum number of 10 at 1/4/2019 6:44:38 PM
Number Counter 6 has reached its maximum number of 11 at 1/4/2019 6:44:38 PM
[…] and so on…”

using System;
using System.Collections.Generic;
/// <summary>
/// Example use of events in c#
/// Author: Konstantinos Sfikas
/// Date: January 2019
///
/// In this example there are 10 event publishers and 1 event subscriber.
/// The event publishers are all instances of the NumberCounter class,
/// while the event subscriber is an instance of the Notifier class.
///
/// As soon as any of the NumberCounter instances reaches its maximum number,
/// the MaxNumReached event is raised, and the Notifier instance responds to it
/// by printing some information to the console.
///
/// </summary>
namespace EventsExample
{
public class EventsTest
{
static void Main(string[] args)
{
Random rand = new Random();
// instantiate the notifier (event subscriber)
Notifier notifier = new Notifier();
List<NumberCounter> numberCounters = new List<NumberCounter>();
// - create 10 instances of the NumberCounter class,
// - set their MaxNum property to a random value (10 to 20),
// - subscribe the notifier's Notify method to all of the NumberCounter instances
// - and store them in the numberCounters list
for (int i = 0; i < 10; i++)
{
// - create an instance of the number counter class
// - with a random value (10 to 20) for the MaxNum property
NumberCounter numberCounter = new NumberCounter(
i,
0,
rand.Next(10, 20) // MaxNum is set to a random value (10 to 20)
);
// subscribe the Notify method of the notifier object
// to the numberCounter's MaxNumReached event
numberCounter.MaxNumReached += notifier.Notify;
// - store the numberCounter in the numberCounters list
numberCounters.Add(numberCounter);
}
// - increase the value of all number counters 20 times,
// to ensure that all of them reached their maximum value.
for (int i = 0; i < 20; i++)
{
foreach (var nc in numberCounters)
{
nc.IncreaseNumber();
}
}
// wait for user input to end the programme
Console.ReadKey();
}
}
// event subscriber
public class Notifier
{
// - This method prints a description of the event to the console.
//
// - Note that it has the same signature as the MaxNumReached
// event's delegate (EventHandler<MaxNumEventArgs>)
//
// - Having the same signature (same return type and same parameters list)
// as the event's delegate, is a prerequisite so that this method can
// subscribed to the specific event.
public void Notify(object sender, MaxNumReachedEventArgs ea)
{
Console.WriteLine(
String.Format(
"Number Counter {0} has reached its maximum number of {1} at {2}",
ea.id,
ea.num,
ea.eventTime.ToString()
)
);
}
}
// NumberCounter: event publisher class
// This class has only one public method (IncreaseNumber)
// which increases the value of the _num parameter by one.
// As soon as the value of _num is equal to _maxNum,
// the MaxNumReached event is raised.
public class NumberCounter
{
// event declaration:
// Note that the event uses the EventHandler delegate type and that the
// custom type of event arguments (MaxNumReachedEventArgs) is used as a
// type parameter.
public event EventHandler<MaxNumReachedEventArgs> MaxNumReached;
// fields
private readonly int _id;
private int _num;
private readonly int _maxNum;
// properties
public int ID { get { return _id; } }
public int Num { get { return _num; } }
public int MaxNum { get { return _maxNum; } }
// constructor
public NumberCounter(int id, int initValue, int maxValue)
{
_id = id;
_num = initValue;
_maxNum = maxValue;
}
// IncreaseNumber: method for increasing the number of the number counter
public void IncreaseNumber()
{
if (Num < MaxNum)
{
_num += 1;
if (Num == MaxNum)
{
OnMaxNumReached();
}
}
}
// OnMaxNumReached: method for raising the MaxNumReached event
//
// The method's name is On + [Event Name]:
// this is the standard way of naming event raising methods
// The method also performs a null check, to ensure that
// there are subscribers to the event, before raising it.
private void OnMaxNumReached()
{
// if there is at least one subscriber to the event,
// then invoke it (raise it)
if (MaxNumReached != null)
{
MaxNumReached.Invoke(
this,
new MaxNumReachedEventArgs()
{
id = ID,
num = Num,
eventTime = DateTime.Now
}
);
}
}
}
// Custom event arguments definition:
//
// EventArgs is a class that is meant to represent the data that the
// event is carrying.
//
// In its pure form, EventArgs contains no parameters at all.
// However, by creating a subclass of the EventArgs class, we can
// include all the necessary fields that we want to use when
// raising the MaxNumReached event.
public class MaxNumReachedEventArgs : EventArgs
{
public int id;
public int num;
public DateTime eventTime;
}
}
view raw EventsTest.cs hosted with ❤ by GitHub

Remarks

While making this case study and writing this blog post, two aspects of using events became more apparent to me, and I decided to mention them here, as an epilogue.

The benefit of using events:

Given this specific example, one may wonder: “why use events, at all?”. This is a legitimate question, in this simplistic scenario. After all, we could just provide a reference of the notifier to every one of our numberCounters, so that they could directly call the Notify method themselves, as soon as they reached their maximum number.

However, using the event pattern allows us to decouple the “event” of reaching a maximum number from a specific reference to the Notify method of the Notifier class. This is very useful in case we may want to expand the “effects” of our event. Imagine, for example, that we added another kind of event subscriber named EventDataSaver, that contains a method called SaveEventData that can save the event data to a file, instead of just printing them on the console.

By using the event pattern, it is very easy to do so, without altering the NumberCounter class, at all. We just make sure that the SaveEventData method has the same signature (return type and arguments) as our event’s delegate and then subscribe the EventDataSaver to the MaxNumReached event of all of our numberCounters.

Events vs Delegates

Events, in c#, are really similar to delegates. An event’s definition and declaration always relies on an underlying delegate which provides the signature for subscribing methods to it and its general use is quite similar to that of a delegate.

Many people are confused by their similarities (a simple google search might convince you about this fact) and I cannot say that I am 100% aware all of their differences. Apart from their formal use and their general technical differences, however, I have spotted one difference that seems quite important:

The fact that events can only be invoked from within the class that they were defined in. This property of events is a useful restriction, because it allows one to expose the event outside the class (to allow subscribers to subscribe to it), but still keep its usage protected from accidental misuse. In my opinion, this technical limitation is also an indicator of how events are supposed to be used.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.