Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use EventHandler<T> and/or the EventArgs delegate pattern?

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.

like image 449
The Communist Duck Avatar asked May 18 '11 17:05

The Communist Duck


People also ask

Is an EventHandler a delegate?

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.

Why is EventHandler t a useful generic type?

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.

Which is the best place to subscribe event handler to an event?

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.

What is the difference between event and delegate in C#?

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.


1 Answers

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);
like image 163
ChaosPandion Avatar answered Oct 12 '22 05:10

ChaosPandion