Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "btn.Click += new RoutedEventHandler (ButtonClick)" and "btn.Click += ButtonClick"? [duplicate]

Tags:

c#

wpf

In C#, when registering a event handler, you have two options (btn is of type System.Windows.Controls.Button):

btn.Click += new RoutedEventHandler (ButtonClick) and

btn.Click += ButtonClick.

What's the semantic difference between them and their implications?

like image 815
Daniel Albuschat Avatar asked Jun 18 '13 09:06

Daniel Albuschat


2 Answers

The first version will compile without errors on all versions of .Net.

The second version will only compile on .Net 2 or later.

And that's the only difference. The second version is just some syntactic sugar introduced with .Net 2.

It's known as Method Group Conversion. See here for details:

http://mike-ward.net/blog/post/00020/anonymous-methods-method-group-conversions-and-eventhandler

like image 111
Matthew Watson Avatar answered Sep 28 '22 22:09

Matthew Watson


As I understood it, nothing, the compiler will infer the delegate type and wrap it for you automatically, it's just a shorthand way of doing it (because who really wants to type it all out).

like image 29
Lloyd Avatar answered Sep 28 '22 21:09

Lloyd