Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should events in C# take (sender, EventArgs)?

Tags:

c#

.net

events

It's known that you should declare events that take as parameters (object sender, EventArgs args). Why?

like image 954
ripper234 Avatar asked Sep 19 '08 19:09

ripper234


People also ask

What is event in C language?

For events you need event loop, which detects that the actual event (say, data from network) happens, and then generates the the software event structure and calls appropriate event handler, or in more complex systems, chain of event handlers, until a handler marks the event accepted.

Why do we need events in C#?

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Why do we need event handling?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.


3 Answers

This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event.

Edit: Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern.

like image 150
Greg Hurlman Avatar answered Oct 12 '22 17:10

Greg Hurlman


Actually this is debatable whether or not this is the best practice way to do events. There is the school of thought that as events are intended to decouple two segments of code, the fact that the event handler gets the sender, and has to know what type to cast the sender into in order to do anything with it is an anti-pattern.

like image 21
user6288 Avatar answered Oct 12 '22 15:10

user6288


Because it's a good pattern for any callback mechanism, regardless of language. You want to know who sent the event (the sender) and data that is pertinent to the event (EventArgs).

like image 6
Eric Z Beard Avatar answered Oct 12 '22 15:10

Eric Z Beard