Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do events in .NET use sender as parameter?

Tags:

c#

asp.net

When I add an event handler for a web control in an ASPX page - why does it pass in sender? What is the advantage to using sender versus just referencing the control by its "ID" in the event handler?

I could see if I had a separate class which handled events, and multiple controls were going to be using the event handler. But if I am certain only this control will handle this event, is it bad just to reference the control ID rather than cast sender to my object type?

Thank you!

like image 405
user53885 Avatar asked Nov 28 '22 15:11

user53885


1 Answers

You appear to be looking at .NET eventing just from the ASP.NET angle. The .NET event model is widely used throughout the entire .NET Framework, not just for ASP.NET pages and controls.

This pattern is flexible to allow any (properly intended) object to be the origin of an event, allowing event listeners to "zero in" on the object that raised it for further processing. Remember that events need not only have one origin and one listener/handler.

Pages and Controls are all objects so to make it flexible enough the sender is typed Object. With some programming discipline, one should be able to define the known-types that can raise that event and cast the sender object back to the original type. If it is purely a string Control ID, one would have to find the control with the matching ID which may not be easy in a page filled with a huge hierarchy of controls.

like image 109
icelava Avatar answered Dec 05 '22 02:12

icelava