Changing the default behavior in Visual Studio when auto-generating code for event binding

Usually, when I subscribe to an event, I use the built-in Visual Studio function to generate the method. Therefore, if I want to attach the clicked event to a button after I write += , I press tab once to generate the code after += , and then again on the tab to create an empty method associated with this event.

So, for a button click event, I get something like this:

 button.Clicked += new EventHandler(button_Clicked); void button_Clicked(object sender, EventArgs e) { throw new NotImplementedException(); } 

Since I prefer a shorter syntax for binding an event handler, I always go back to the auto-generated line and change it like this:

 button.Clicked += button_Clicked; 

My question is simple. Is there a way to make VS automatically prefer this syntax by default, so I don’t need to manually switch and change this every time.

This applies to both VS2008 and VS2010.

+4
source share
3 answers

No, it is not under your control to change.

It’s easier for them to keep it in the old style so that it always works no matter which version of C # it targets. Otherwise, they would have to make the generated code conditional on the C # version, and I can imagine that this is just more work than it's worth. Unfortunately, this code generation is not extensible, so you need to change your code yourself.

You can try third-party add-ons, such as the ReSharper product, to get additional performance, because they implement many interesting functions by accessing the object modally and modifying it.

+2
source

As far as I know, no.

I'm sure I read it somewhere reputable, but I can’t remember where right now

+1
source

It annoys me too. However, I use ReSharper, which offers several options when creating event handlers, such as creating a new method, adding a lambda method or anonymous method, or using any existing methods that have the appropriate signature.

In addition, R # highlights any redundant code and makes it easy to remove it from either one site or from the entire project / solution.

+1
source

All Articles