Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

events

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?

like image 363
Thomas Avatar asked Dec 21 '09 21:12

Thomas


People also ask

What does EventArgs E mean in C#?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

What is EventArgs in VB?

EventArgs is the base class of all event arguments and doesn't say much about the event. Several events use a derived class to supply more data, eg. a KeyPress event uses the KeyEventArgs class which contains the actual key pressed in its KeyChar property.

What is event argument in C#?

The general prototype for an event in C# is: private void EventName (object sender, EventArgs e) For some controls, the event argument may be of a type derived from EventArgs and may expose properties specific to that event type.

What base class do you use to convey information for an event?

EventArgs is a base class for conveying information for an event. For reusability, the EventArgs subclass is named according to the information it contains rather than the event for which it well be used.


2 Answers

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.

like image 128
jupi Avatar answered Sep 28 '22 08:09

jupi


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.

like image 32
nitzmahone Avatar answered Sep 28 '22 08:09

nitzmahone