When you subscribe to an event in code, Visual Studio automatically completes the code after +=
and generates the appropriate event handler:
button.Click += new EventHandler(button_Click); // ↑_____auto generated code_____↑
Notice how it explicitly creates the delegate instance: even though method groups are implicitly convertible to delegates since C# 2, the IDE behavior still hasn't changed in VS2010.
So I'd like to know, is there a way to generate code like this instead?
button.Click += button_Click;
EDIT
just to make things clear to everyone: the code above is not in a designer file (I wouldn't care which syntax is used if it was the case). It's the snippet that is triggered when you type +=
after an event name and press TAB
EDIT2
I reported this as a suggestion on Connect, you can vote for it if you also want the current behavior to be changed
From the Class Name drop-down list at the top of the Code Editor, select the object that you want to create an event handler for. From the Method Name drop-down list at the top of the Code Editor, select the event. Visual Studio creates the event handler and moves the insertion point to the newly created event handler.
An event handler is the code you write to respond to an event. An event handler in Visual Basic is a Sub procedure. However, you do not normally call it the same way as other Sub procedures. Instead, you identify the procedure as a handler for the event.
In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.
The suggestion on Connect has been marked as fixed, so the new behavior should be included in the next public build of VS11.
EDIT: just checked, it is indeed included in the beta.
Thanks for clarifying your question. Unfortunately, there isn't a way to configure or customize the event hookup code that is generated by the C# language service. To make matters worse, the Generate Method Stub feature won't work on an event hookup either -- though it should, and that is already fixed for the next release of Visual Studio.
Sorry that there isn't a better story for this particular feature. :-(
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