'It is possible to pass data to EventArgs without creating derived class?

I am a bit confused. I know I can create class derived from EventArgs in order to have custom event data. But can I employ the base class EventArgs somehow? Like the mouse button click, in the subscriber method, there is always "EventArgs e" parameter. Can I create somehow the method that will pass data this way, I mean they will be passed in the base Eventargs?



Solution 1:[1]

You can use the EventArgs class through the Generic Types approach. In this sample, i will use the Rect class with as return type:

public EventHandler<Rect> SizeRectChanged;

Raising the event:

if(SizeRectChanged != null){
   Rect r = new Rect(0,0,0,0);
   SizeRectChanged(this,r);
}

Listening the event:

anyElement.SizeRectChanged += OnSizeRectChanged;

public void OnSizeRectChanged(object sender, Rect e){
    //TODO abything using the Rect class
    e.Left = e.Top = e.Width = e.Height = 50;
}

So, don't need to create new events classes or delegates, simply create a EventHandler passing the specific type T.

Solution 2:[2]

Nope. The EventArgs base class is just a way to allow for some standard event delegate types. Ultimately, to pass data to a handler, you'll need to subclass EventArgs. You could use the sender arg instead, but that should really be the object that fired the event.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jupi
Solution 2 nitzmahone