Posted By: ploe | Jun 25th, 2008 @ 7:04 AM
page 1 of 1
Comments: 12 | Views: 1316
Is there a difference between these two lines?

button.Click += new EventHandler(OnButtonClick);
button.Click += OnButtonClick;

Both compile and work from what I can see. Do they behave differently? Is one preferred over the other?
Yggdrasil
Yggdrasil
Pour me a cab, 'cause I can't drink no more.
They're identical. The second is simply a compiler trick that infers the right delegate automatically, so behind the scenes the second form is converted to the first.
yea, added in C# 2.0 and called "delegate inference" or something close to that...
littleguru
littleguru
<3 Seattle

Exactly... using ILDASM will show you that both are the same once compiled.

Bas
Bas
It finds lightbulbs.
Why does Visual Studio still come up with the "New EventHandler(button_Click); (Press tab to insert)" tooltip when that approach is no longer necessary?
evildictaitor
evildictaitor
if( !succeed( try() ) ) { while(true) try(); }
For big functions it's still nice, and you'll notice that at the point where TAB builds the stub, it's also got the button_Click bit highlighted, so you can immediately type (o,e) => someFunc(e)
TommyCarlier
TommyCarlier
I want my scalps!
And if you press tab a second time, the method is created for you!
Bas
Bas
It finds lightbulbs.
So why didn't they change it to just say "button_Click(); (Press Tab to insert)"?
evildictaitor
evildictaitor
if( !succeed( try() ) ) { while(true) try(); }
I suspect they just haven't implemented it yet.

If they're sensible they should have it as an option, because lovely as lambda functions are, not everyone likes them.

The bit that impressed me was that lambda functions are in fact entirely syntactic sugar, and therefore also work under .NET 2.0, so you're right, there's a good argument that this should be changed in future versions of VS/C#.
TommyCarlier
TommyCarlier
I want my scalps!
You can even make extension methods work in .NET 2.0, if you use a little (unsupported) trick.
Bas
Bas
It finds lightbulbs.

I get a 404 there. But you can actually get a lot of purely syntactic stuff, like automatic properties and such, to work in .NET 2.0 if you just use a 3.0 compiler and target the 2.0 framework. Does it work like that?

TommyCarlier
TommyCarlier
I want my scalps!

I fixed the link.

The problem is that the compiler needs the ExtensionAttribute-class, which is implemented in System.Core.dll (new in .NET 3.5). The solution is to add a class named ExtensionAttribute with the namespace System.Runtime.CompilerServices to your project. Like this:

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}
Bas
Bas
It finds lightbulbs.

Huh, that's pretty cool. Thanks for the tip!

page 1 of 1
Comments: 12 | Views: 1316
Microsoft Communities