tags:

views:

69

answers:

3

This is a simple question. If the content of two lambda expressions in the same class are exactly the same, will the compiler generate and use one backer method, or will it generate a method for each instance?

Example

ctl.MouseOver += (sender,e) => UpdateStatus();
ctl.MouseOut += (sender,e) => UpdateStatus();

Does this generate one or two backer methods?

p.s. I know that you can create another method HandleUpdate(object,EventArgs) and attach an event to that. But I'm more curious about what actually happens with the compiler.

+1  A: 

Its been my experience that it generates two copies. There may be some optimization that I haven't hit, but every time I've checked in my code, I've gotten two copies.

If you're going to have duplicate handling, I'd recommend creating a HandleUpdate method, as you mentioned.

Reed Copsey
+2  A: 

It's complicated. IIRC (and I may be way off here, it's been a while since I've read the exact details), two expressions can "resolve" to the same instance, but in practice it's very hard to do, because the expressions tend to create closures that are slightly different and need to be hoisted with the expression. Basically, the call site is important too.

Joel Coehoorn
+1  A: 

Having the lambda expressions in the same class isn't sufficient to consider the expressions identical, as the compiler takes into account which method they're invoked within as well.

Use the same expression twice within the same method, and you'll possibly get the same instance, but I wouldn't write code reliant upon this behaviour.

If you really need to know the current behaviour of the compiler, grab a copy of reflector and have a look at the IL generated.

Bevan