Mu'men Tayyem
Mu'men Tayyem

Reputation: 163

C# built-in events

After reading the following piece of code :

[SerializableAttribute]
public delegate void EventHandler<TEventArgs>
(
   object sender,
   TEventArgs e
)

Why did not Microsoft guys give Object type for the "e" parameter just like the sender parameter? am I missing something major here?

Upvotes: 2

Views: 109

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062770

If they had done that, people would constantly have to cast the args parameter. The point is that you can do things like:

public event EventHandler<SomeInterestingEventArgs> SomeEvent;

and:

obj.SomeEvent += (sender, args) => Console.WriteLine(args.SomeSpecificProperty);

This is a convenient way of replacing the need to declare:

public delegate void SomeInterestingEventHandler(
    object sender, SomeInterestingEventArgs args);

which is what you would have to do without this.

Upvotes: 7

Dave
Dave

Reputation: 3017

You can make your own event args class that has some useful properties on it. Like the mouse click event args (can't remember the proper name) has an X and Y prop to tell you what point was clicked. Thanks to generics you don't need the casting you would with just a plain old object. You'd just have

MyEventHandler<MouseClickedEventArgs>(object sender, MouseClickedEventArgs e). 

And everything is strongly typed

Upvotes: 3

Related Questions