Index
Now that we've seen what delegates are, let's move on to what events are since they are completely related. With C# we can use event driven programming
.
Before continuing, let me mention I've used events in two or three projects, all of them desktop applications. This shows that they're not extremely popular, but you need to be prepared and understand what you're reading when programming.
1 - What are events
The concept of event
in .NET is very similar to what an event might be in a company. For example, Google announces an event to showcase its latest product. The company will notify users via email that there's a new product.
In this scenario, Google is the publisher
, who creates an event, and users become subscribers
who participate in the event.
Events are actions, such as clicking a button, moving the mouse, etc. But we're not restricted to the predefined interface events, we can also create our own custom events.
Another way to describe events is that an event is a message sent by an object to indicate that a certain action is going to occur. As mentioned above, it could be clicking or moving the mouse.
In C#, events follow the publisher-subscriber
pattern.
1.1 - The Publisher
In C#, the publisher is the element that determines when an event has been triggered. It's the object that contains the event definition and its delegate. If you don't remember what delegates are, you can check the following link.
The publishing class will invoke the event object and notify other objects.
1.2 - The Subscriber
This is an object that receives the event and provides an event handler
, which will be the method executed when the event occurs.
1.3 - The Event
Finally, we have the event itself. This is the encapsulation of a delegate within the Publisher class.
2 - Declaring an Event in C#
Now that we have the theory more or less clear, let's move on to the practical part. In general terms, an event is just an encapsulated delegate.
That's why the first thing we have to do is declare a delegate. To stay within a class structure, I have created a class called Editor and in it, we’ll create our delegate.
public class Editor
{
public delegate void EjemploEvento();
public EjemploEvento ejemploEvento;
}
To specify that it's an event, we just need to use the event
keyword before declaring the delegate variable:
public class Editor
{
public delegate void EjemploEvento();
public event EjemploEvento ejemploEvento;
}
3 - Event Example in C#
The easiest way to understand this will be to use an example of creating events in C#.
Note that to subscribe to an event, you must use “+=
”, and to unsubscribe, “-=
”. We'll see how shortly.
3.1 - Creating the Publisher
As an example, we are going to use the logic of what could be a calculator, which we've previously seen as a clear example.
To keep things simple, we'll just look at addition and subtraction.
public class EditorCalculadora
{
public delegate void EjemploDelegado();
public event EjemploDelegado ejemploEvento;
public void sumar(int a, int b)
{
if (ejemploEvento != null)
{
ejemploEvento();
Console.WriteLine("La suma es: {0}", a + b);
}
else
{
Console.WriteLine("No estas suscrito a los eventos");
}
}
public void Restar(int a, int b)
{
if (ejemploEvento != null)
{
ejemploEvento();
Console.WriteLine("La resta es: {0}", a - b);
}
else
{
Console.WriteLine("No estas suscrito a los eventos");
}
}
}
As we can see, we have the EditorCalculadora
class, which contains a delegate
and an event
. In addition to these two elements, there are two methods: one for addition and another for subtraction.
If we look inside either one, we see that the first thing we do is check if the event is not null
(i.e., it exists) before executing it.
3.2 - Creating the Subscriber
For the subscriber, we create a class called SuscriptorCalculadoraVirtual
that will subscribe to the events.
First, we need to define the variables and constructor, as well as the methods we want to use.
To subscribe to the events, we must create a method that matches the delegate in the Editor
class. We'll create a method that receives no parameters and returns void
. This method will be executed every time the Publisher fires an event.
public class SuscriptorCalculadoraVirutal
{
EditorCalculadora editor;
private readonly int A;
private readonly int B;
public void EjemploEventHandler()
{
Console.WriteLine("Se va a imprimir el resultado:");
}
public SuscriptorCalculadoraVirutal(int a, int b)
{
editor = new EditorCalculadora();
A = a;
B = b;
}
public void ResultadoSuma()
{
editor.sumar(A, B);
}
public void ResultadoResta()
{
editor.Restar(A, B);
}
}
As we can see, in the constructor we define the constructor
, variables, and the Editor.
Now, let's try running the code:
SuscriptorCalculadoraVirutal calculadoraVirutal = new SuscriptorCalculadoraVirutal(3, 2);
calculadoraVirutal.ResultadoSuma();
calculadoraVirutal.ResultadoResta();
As we can see, our code will print No estas suscrito a los eventos
And that's because we haven't subscribed to the events.
To subscribe to an event in C#, you need to specify the parent object's event property and link it using +=
with the handler we created in our subscriber class, which matches the delegate from the publisher.
In our example, we change the subscriber class constructor to the following:
public SuscriptorCalculadoraVirutal(int a, int b)
{
editor = new EditorCalculadora();
A = a;
B = b;
editor.ejemploEvento += EjemploEventHandler;
}
And if we run the code, we see the following result:
Se va a imprimir el resultado:
La suma es: 5
Se va a imprimir el resultado:
La resta es: 1
Which allows us to see that now we ARE subscribed to the events.
Conclusion
- We use the
event
keyword along with delegates to declare events. - We should check if an event is null before executing it, since this could cause an error.
- The publisher determines when an event is triggered. The subscriber determines what action or method to execute when that event happens.
- To subscribe to an event, use the
+=
operator. To unsubscribe, use-=
. - To execute an event, you need to invoke the delegate.
- You can include events in interfaces.
- Events are mostly used when working with interfaces to define actions to execute on clicks or other interaction. They’re also very common outside .NET for web development.
If there is any problem you can add a comment bellow or contact me in the website's contact form