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.
The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.
The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. You simply provide the type of the event data object as the generic parameter.
To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.
An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With