10

Reading my C# book, it talks about using events/delegates (I am assuming I am right in thinking an event is the equivalent of a public delegate which has no member variable access) in a pattern liked by MS:

public delegate Something(object o, EventArgs e)

And then goes onto explain about EventArgs<T> which basically removes the need for the delegate declaration:

public EventHandler<SomeEventArgs> events

Which is the same as (I think)

private delegate Something(object o, SomeEventArgs e);

public event Something events;

Is it a good idea to use EventHandler? I can see why sending the object could be useful, but not all the time - and a lot of the time, the EventArgs may just become annoying to deal with.

PrettyPrincessKitty FS
  • 6,117
  • 5
  • 36
  • 51
  • 3
    Personally I am not a fan of the event handler pattern in its current form. In fact your last sentence sums up my reasons quite nicely. – ChaosPandion May 18 '11 at 17:10

1 Answers1

10

Microsoft has definitely pushed some great patterns that has made working with C# a pleasant experience. That being said, I recommend you write your event handlers to be convenient for your client code rather than writing a lot of code just to meet a pattern.

delegate void ClientMessageHandler(IClient client, IMessage message);
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • 1
    Isn't this almost exactly the same as my 3rd code part, except with IClient instead of object and IMessage instead of EventArgs? If so, I don't see what I gain from this except having to make sure I implement IClient and IMessage...knowing me, I'm missing something big ;-) – PrettyPrincessKitty FS May 18 '11 at 17:22
  • 2
    @The Communist Duck - The difference is that you are never quite sure what `sender` is without checking the documentation. The event raiser also has to initialize an `EventArgs` object just to wrap the `IMessage` instance. This delegate signature speaks for itself. – ChaosPandion May 18 '11 at 17:24
  • See also the following for another approach: http://stackoverflow.com/questions/809609/c-sharp-simple-event-raising-using-sender-vs-custom-eventargs – Mike Rosenblum Aug 29 '12 at 16:15