Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I customize automatic event handler generation in Visual Studio?

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

like image 697
Thomas Levesque Avatar asked Dec 17 '10 14:12

Thomas Levesque


People also ask

How do you create event handlers with visual studio net?

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.

What is an event handler in Visual Studio?

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.

What is an event handler How is it designed?

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.


2 Answers

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.

like image 56
Thomas Levesque Avatar answered Oct 22 '22 00:10

Thomas Levesque


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. :-(

like image 42
Dustin Campbell Avatar answered Oct 22 '22 01:10

Dustin Campbell