Skip to main content
gamedev.net
🔒 Locked

EventHandler confusion

Started by danromeo Mar 21, 2009 at 1:15 PM 0 replies 800+ views
Original Post
danromeo
danromeo
Hiya, thanks for reading this. Two questions: 1. What is the difference between these two statements? Window.ClientSizeChanged += new EventHandler(Window_ClientSizeChanged); Window.ClientSizeChanged += Window_ClientSizeChanged; 2. I've seen like 7 different ways to handle events....eventhandler's, delegates, and then a myraid of different ways of declaring and using them. What is the difference between and eventhandler and a delegate? Does anybody know of any article or tutorial that straightens out this confusion? THANKS
MJP
MJP
1. There is no difference. Back in C# 1.1, you had to add an event handler by explicitly creating a new delegate using "new". C# 2.0 added a feature called "Delegate Inference", which lets you assign a method to an event or delegate without using "new" and wrapping it in the delegate name. Both give the same exact result, and compile to the same IL.

2. An event handler is a delegate. See events in C# are just multicast delegates: when you fire off an event it says "okay, let call all the delegates that are assigned to me".

Now don't confuse with with EventHandler, which is type of delegate that's part of the .NET Framework Library. See whenever you declare an event, you have to also supply the type of delegate that has to be used for event handlers. EventHandler is considered the most "basic" type of delegate used for events in the .NET Framework Library. So for instance you could create a custom event like this:

class McDonalds{    public delegate void CheeseBurgerDelegate(CheeseBurger burger);    public event CheeseBurgerDelegate BurgersReady;}


Notice how you create the delegate first describing the layout of a method that can subscribe to the event, then you actually make the event.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.