views:

69

answers:

2

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(MailManager sender, NewMailEventArgs 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 Object.

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

+7  A: 

Generics did not exist in C# version 1.

John Saunders
+3  A: 

Even if generics were implemented around this, you would still have the same problem. Inside your MailManager object, you would call this.EventName<MailManager>(this, args), and so it would only match people who subscribed to that typed event.

Granted, they could rework the entire way that methods and events are looked up by the CLR so that it's very loose. Then we would have Javascript# instead of C#, though :p

JustLoren
+1, this is the correct answer. Generics can't solve the problem of base classes raising events. Which is *very* common.
Hans Passant