Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event signature pattern in .net

Tags:

.net

events

What's the point in the standard pattern for event delegates in .net? I.e. the EventHandler predefined delegate? Why not just choose the most appropriate signature for the requirement?

Edit: And furthermore, is it necessary to slavishly follow Microsoft's example in all cases?

like image 433
Gaz Avatar asked Oct 29 '08 15:10

Gaz


2 Answers

In C# 1.0 the convention didn't make a lot of sense. In C# 2.0, where there is a certain amount of delegate variance, it makes more sense.

If you have an event handling method which doesn't really care about the parameters, e.g.

public void SaveDocument(object sender, EventArgs args)
{
    // Save the document here
}

you can now use that method to subscribe to any event which follows the convention, even if the actual sender or args are more strictly typed. This means you can use the same handler for a keyboard event, a button click etc.

like image 121
Jon Skeet Avatar answered Oct 15 '22 09:10

Jon Skeet


It's mainly for consistency and versioning—with the sender paramater as always System.Object and the args parameter as always a System.EventArgs, or a dervied class thereof, you can change the sender argument passed to it as well as change the EventArgs type afterwards without breaking any existing code.

The whole .NET eventing idiom was designed to support component-based development, where the calling code is not under control of the developer of the component with the events.

like image 42
Mark Cidade Avatar answered Oct 15 '22 08:10

Mark Cidade