Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

Changing the default behaviour in Visual Studio when autogenerating code for binding to an event

Usually when I subscribe to an event, I use the Visual Studio builtin function to generate the method. So if I want to bind a clicked event to a button after I write += I click tab one time to generate the code after +=, and then tab again to create the empty method associated with this event.

So for a button clicked event, I will end up with something like this:

button.Clicked += new EventHandler(button_Clicked);

void button_Clicked(object sender, EventArgs e) {
  throw new NotImplementedException();
}

Since I prefer the shorter syntax for binding the eventhandler, I always go back to the autogenerated line, and change it to look like this:

button.Clicked += button_Clicked;

My question is simply. Are there any way to make VS automatically prefer this syntax over the default one, so I don't manually have to go and change this every time.

This applies both for VS2008 and VS2010

Upvotes: 4

Views: 203

Answers (3)

Phil Wright
Phil Wright

Reputation: 22906

No, this is not under your control to modify.

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

You could try third-party extras such as the ReSharper product to gain extra productivity as they implement many cool features by accessing the object modal and modifying it.

Upvotes: 2

Drew Noakes
Drew Noakes

Reputation: 310967

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

Also, R# will highlight any redundant code and let you remove it easily, either from a single site or from the entire project/solution.

Upvotes: 1

Benjol
Benjol

Reputation: 66541

As far as I know, no.

I'm sure I've read it somewhere authoritative, but I can't remember where right now

Upvotes: 1

Related Questions