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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With