Why Is the sender type null when dealing with events

Posted by ChloeRadshaw on Stack Overflow See other posts from Stack Overflow or by ChloeRadshaw
Published on 2010-05-28T14:49:39Z Indexed on 2010/05/28 14:51 UTC
Read the original article Hit count: 164

Filed under:

From C# Via CLR:

Note A lot of people wonder why the event pattern requires the sender parameter to always 
be of type Object  After all, since the MailManager will be the only type raising an event with a 
NewMail EventArgs object, it makes more sense for the callback method to be prototyped like 
this:
void MethodName(Mai l Manager sender, NewMail EventArgs e);
The pattern requires the sender parameter to be of type Object mostly because of inheritance  
What if Mai lManager were used as a base class for SmtpMailManager? In this case, the callback  
method should have the sender parameter prototyped as SmtpMailManager instead of 
Mail Manager, but this can’t happen because SmtpMai lManager just inherited the NewMai l 
event  So the code that was expecting SmtpMail Manager to raise the event must still have to 
cast the sender argument to SmtpMailManager  In other words, the cast is still required, so the 
sender parameter might as well be typed as Obj ect 
The next reason for typing the sender parameter as Obj ect is just fexibility  It allows the delegate to be used by multiple types that offer an event that passes a NewMail EventArgs object  
For example, a PopMai lManager class could use the delegate even if this class were not derived 
from Mail Manager

I just simply cannot understand why the sender is an object - Why can it not be generified? so most of the time we do not need to do generic casts

© Stack Overflow or respective owner

Related posts about c#