[ XF9 ]

Eventhandler (C#)

Posted on in C#.

Eventhandlers are a very handy thing to have to let other components know something happend.

This is the C# version, if you are looking on how to implement Eventhandler in C++ go here

The following example uses a custom event with two parameter, defined as followed:

public class CustomEvent : EventArgs
{
    public int EventArgInt { get; set; }
    public string EventArgString { get; set; }
}

Two things are required to use this event in a class: a public event variable and a function to emit the event. In the following example the public event varaible is called TheEvent and the emitting function EmitEvent. The function Emit displays how to call the event funtion.

class Caller
{
    // public event to hook on
    public event EventHandler<CustomEvent> TheEvent;

    // function to emit an event
    protected virtual void EmitEvent(CustomEvent e)
    {
        EventHandler<CustomEvent> handler = TheEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    // example for emitting an event
    public Emit()
    {
        CustomEvent cevent = new CustomEvent();
        cevent.EventArgInt = 42;
        cevent.EventArgString = "forty two";
        EmitEvent(cevent);
    }
}

In order to respond the event a class hooks to the public event variable of the caller:

    class Responder
    {
        public Responder()
        {
            Caller c = new Caller();
            c.TheEvent += Respond;
        }

        public void Respond(object sender, CustomEvent e)
        {
            // handle the event
        }
    }

Write a reply or comment

Your email address will not be published.