5

I was showing some of my code to a junior programer, and he asked me why am I registering functions for event handling like this:

button1.Click += new RoutedEventHandler(button1_Click);

and not like this:

button1.Click += button1_Click;

The only thing I could say was: because you just write += and press tab two times...

What is the difference between those two metods (if there is a difference)?

3
  • 1
    I would normally migrate this to Stack Overflow, however I know for a fact that it would simply be a duplicate there. However, I think it's OK for here too. Commented Feb 17, 2011 at 12:40
  • thx. I assumed answer will be that its thing of taste. so i posted it here. Commented Feb 17, 2011 at 13:03
  • 1
    In VS2012, it automatically creates the second one now. Commented Mar 7, 2013 at 16:47

2 Answers 2

6

The answer depends on what version of C# you are using.

The early versions required the new RoutedEventHandler while the newer versions don't.

They compile to the same code.

0
3

Personally, if what you're doing in the handler is really short and not shared with any other events, I like this form:

button1.Click += (sender, e) =>
{
    DoSomethingAwesome(e.RoutedEvent);
    e.Handled = true;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.