I am studying C # but I got to the subject of Delegates and Events, I know it is a delegate and how it works:
The delegate is like an "encapsulator" of functions, where we can reference a method through an instance of the delegate.
I searched the MS page, in several tutorials and also in this question What are the Delegates in C #?
An example for delegate use I have it like this: (ignore the name of the namespace)
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 managed to understand the operation and apply it to use between classes
Now yes, my question is:
What is the event for?
According to Microsoft and logic of any human, an event is a message sent to notify that something happened. But if I already have the delegate , with which I can "send" functions between objects, by means of an instance of the delegate, this way I could notify anything of and from any class, no?
So how is the use of event ?
* By the way, I know there are a couple of questions on this topic, C # - Understanding events, eventhandlers and delegates , but I can not understand them, for that reason, I open another question ...
Thank you!