C # Events (difference with respect to a Delegate)

1

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!

    
asked by Victor Alfonso Pérez Espino 05.01.2019 в 02:35
source

1 answer

1

The event is an encapsulation of a delegate.

When you access an event through an intance of your class, it only allows you to subscribe or unsubscribe from the event.

What is the purpose of the event?     To send notifications to those who are subscribed to said event.

So how is the use of event?

public delegate void MiDelegado(string input);

public class MiClase
{
    public MiDelegado MiDelegado { get; set; }

    public event MiDelegado MiDelegadoEvent;

    public void InvokeEvent(string input)
    {
        MiDelegado.Invoke(input);

        MiDelegadoEvent(input);
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var instance = new MiClase();

        // Éstas son las dos únicas operaciones permitidas desde la instancia
        // Eliminar la subcripción al evento
        instance.MiDelegadoEvent -= Instance_MiDelegadoEvent;
        // Subscribirse al evento
        instance.MiDelegadoEvent += Instance_MiDelegadoEvent;

        // Ésta llamada la puedes hacer en cualquier método de tu clase o donde estes usando la intancia.
        instance.InvokeEvent("Invocando el evento");

        // De esta forma tienes acceso total a todas las funcionalidades del delegado 
        // Haciendo esto rompes el Pilar de Encapsilación.
        instance.MiDelegado.Invoke("cadena");
        instance.MiDelegado.DynamicInvoke();

    }

    private static void Instance_MiDelegadoEvent(string input)
    {
        Console.WriteLine(input);
    }
}
    
answered by 05.01.2019 / 04:13
source