- Home /
Concrete Delegate vs EventHandler for Events
For events i can do 2 ways:
1) public delegate void Event_Handler ();
public event Event_Handler Some_Event;
2) public event EventHandler Some_Event;
I know that 2) variant better because no need to define concrete delegate "public delegate void Event_Handler ();" But it not better because i need to write in all methods - subscribers parameters:
void Method_For_Event (object sender, EventArgs event_args)
So what variant you think better and why?
Answer by Bunny83 · Oct 03, 2015 at 06:24 AM
Well, as always it depends on what you need. The EventHandler type is just a predefined general purpose delegate type that is commonly used by most GUI controls of the .NET framework. As most events have some object that is responsible for raising the event (the "sender") and often an event requires some parameters. The EventHandler type is just a generic way to maintain compatibility with other systems.
Your line:
public delegate void Event_Handler ();
Just declares a new delegate type with no parameters and no return type. You would only need to declare that delegate once for your entire project.
However you don't need to declare that delegate at all, since there is already the System.Action
delegate type which is exactly the same as your type. There are also generic versions of that type where you can easily specify parameter types.
For example Action<Vector3, float>
represents a delegate like this:
public delegate void DelegateTypeName (Vector3 v, float f);
So if you just want to declare an event with no parameters you can simply do:
public event System.Action Some_Event;
Furthermore there's also the "Func" type which represents a delegate with a return type.
Func<int, int, string>
will represent
public delegate string DelegateTypeName (int i1, int i2);
Looks like use "Action" and "Func" ins$$anonymous$$d of "delegate" in most cases more comfortable.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Relationship between Events and Update() 2 Answers
Adding single Event listener to multiple ui buttons via scripting 1 Answer