Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event parameter; "sender as Object", or "sender as T"?

When I write public events for my business objects, I've adapted the habit of always passing the instance as "sender as Object", in addition to additional specific parameters. I just asked myself now why am I not specifying the class?

So for you with more experience; Do you ever pass the distinct class as sender in an event? And if so, what are your decision criteria for when this is ok/not ok?

like image 806
bretddog Avatar asked Feb 09 '11 12:02

bretddog


People also ask

What is sender As object E as EventArgs?

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 sender As object E as EventArgs in VB net?

Sender is the object that raised the event and e contains the data of the event. All events in . NET contain such arguments. EventArgs is the base class of all event arguments and doesn't say much about the event.

What is a sender C#?

In the general object, the sender is one of the parameters in the C# language, and also, it is used to create the instance of the object, which is raised by the specific events on the application. That event is handled using the Eventhandler mechanism that is mostly handled and responsible for creating the objects.


1 Answers

Don't be extreme. EventHandler(object sender, EventArgs e) has an object sender so that we can use it in many circumstances. But it doesn't mean a strongly-typed sender is evil. A strongly-typed sender is useful when this delegate is not going to be widely used(like EventHandler) e.g.

public delegate void SaveHandler(Controller sender, EventArgs e);

Now other developers(or someone using your library) can recogonize that the sender have to be a Controller, and they will be glad not to code like this:

public void MySaveHandler(object sender, EventArgs arg)
{
   var controller = sender as Controller;
   if (controller != null)
   {
       //do something
   }
   else
   {
       //throw an exception at runtime? 
       //It can be avoided if sender is strongly-typed
   }
}

And you can even make it generic:

public delegate void SaveHandler<T>(T sender, EventArgs args) 
                                              where T: IController;

It's pure legal and good practice in C#. You should make clear what you want to do, and then choose the better way. Either of them is evil/bad.

like image 157
Cheng Chen Avatar answered Sep 30 '22 20:09

Cheng Chen