Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a generic event raising method

I have a set of events that have the same signature . now I wonder if I can create a generic event handler raising method to do this for all of the events ?

  • is this possible to send an event as <T> ?
like image 568
mohsen dorparasti Avatar asked Sep 28 '12 16:09

mohsen dorparasti


People also ask

How do you raise an event?

Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .

What is EventArgs C#?

The EventArgs class is the base class for all the event data classes. . NET includes many built-in event data classes such as SerialDataReceivedEventArgs. It follows a naming pattern of ending all event data classes with EventArgs. You can create your custom class for event data by deriving EventArgs class.

What is event handler in C# with example?

An event handler is the subscriber that contains the code to handle specific events. For example, an event handler can be used to handle an event that occurs during the click of a command button in the UI. In C#, an event is connected to its handler by an event delegate.

How do you call an event handler in C#?

Invoke(this, e); handler(this, e) will call every registered event listener. Event listeners subscribe with help of the += operator and unsubscribe with -= operator to that event. this is there to give the event listener to know who raised the ThresholdReached event.


2 Answers

If this is all within a single class, you can make a method to raise the event which works with any of them. For example, if your events all were EventHandler<T>, you could use:

private void RaiseEvent<T>(EventHandler<T> eventHandler, T eventArgs)
{
    if (eventHandler != null)
    {
        eventHandler(this, eventArgs);
    } 
}

You could then call this via:

this.RaiseEvent(this.MyEvent, new MyEventArgs("Foo"));
like image 141
Reed Copsey Avatar answered Sep 27 '22 18:09

Reed Copsey


For a static version of Reed Copsey's reply, I created a static class Event:

public static class Event
{
    public static bool Raise<T>(Object source, EventHandler<T> eventHandler, T eventArgs) where T : EventArgs
    {
        EventHandler<T> handler = eventHandler;
        if (handler != null)
        {
            handler(source, eventArgs);
            return true;
        }
        return false;
    }
}

This also assumes your event handlers are of the type EventHandler<T>. The return type was changed from void to bool and returns whether there were any listeners of the event. Rarely used, so feel free to change back to void.

Example usage:

public event EventHandler<FooArgs> FooHappend;

public void Foo()
{
    Event.Raise(this, FooHappend, new FooArgs("Hello World!");
}
like image 37
Vapid Linus Avatar answered Sep 27 '22 19:09

Vapid Linus