I'm studying C# but I got to the topic of Delegates and Events, I already know what a delegate is and how it works:
The delegate is like a "wrapper" for functions, where we can reference a method via an instance of the delegate.
I searched on the MS page, in various tutorials and also in this question What are Delegates in C#?
I have an example for delegate use like this: (ignore the namespace name)
using System;
namespace AdicionEliminacionReferenciasDelegadas
{
delegate void prueba();//contrato, debe tener la misma firma que las funciones que va a recibir
class Program
{
static void Main(string[] args)
{
prueba Test = new prueba(metods.metod1);
Test += metods.metod2;//apilacion de referencias en la instancia Test,
Test();//llamado secuencial de la apilacion (ejecuta las funciones referencias dentro deTest)
Console.WriteLine("--------------------------------------------------------------------\n Llamado entre clases: \n");
ejemplo obj = new ejemplo();
obj.addDelegateStack(metods.metod1);//se añade un metodo de otra clase(estaba probando entre clases)
obj.addDelegateStack(metods.metod2);
obj.ejecutarDeleg(); //ejecuta al atributo Test (miembro de clase) donde están contenidas las referencias, de los 2 metodos agregados arriba
Console.WriteLine("\nEliminacion de metodo 1, el cual se busca y se elimina del ArrayList interno del contenedor delegate .... \n");
obj.deleteDelegateStack(metods.metod1);
obj.ejecutarDeleg();//vuelve a ejecutar ese miembro, para comprobar que se elimina una referencia especifica
Console.ReadLine();
}
}
class ejemplo
{
public prueba Test;
public void addDelegateStack(prueba newDeleg)
{
Test += newDeleg;
}
public void deleteDelegateStack(prueba newDEleg)
{
Test -= newDEleg;
}
public void ejecutarDeleg()
{
Test();
}
}
static class metods
{
public static void metod1()
{
Console.WriteLine("Metodo 1, Estás en clase metods");
}
public static void metod2()
{
Console.WriteLine("Metodo 2, sigues en clase metods");
}
}
}
With this example I was able to understand how it works and apply it to use between classes
Now yes, my question is:
What is the event for ?
According to Microsoft and any human logic, an event is a message sent to notify that something has happened. But if I already have the delegate , with which I can "send" functions between objects, by means of an instance of the delegate, then anything could be notified to and from any class, right?
So how is the use of event ?
*By the way, I already know that there are a couple of questions on this topic, C#- Understanding events , eventhandlers and delegates , but I can't understand them, for that reason, I open another question...
Thank you!
The event is an encapsulation of a delegate.
When you access an event through an instance of your class, it only allows you to subscribe or unsubscribe to the event.
What is the event for? To send notifications to those who are subscribed to said event.
So how is the use of event ?