0

According to Jon Skeet's answer anonymous functions are not guaranteed to return equal delegates:

The C# specification explicitly states (IIRC) that if you have two anonymous functions (anonymous methods or lambda expressions) it may or may not create equal delegates from that code. (Two delegates are equal if they have equal targets and refer to the same methods.)

example of problematic code given

button.Click += (s, e) => MessageBox.Show("Woho");
button.Click -= (s, e) => MessageBox.Show("Woho");

Is this the same case for for extension methods as well? For sake of sample simplicity, lets ignore whether it is good idea to extend string:

var text = "Woho";   
// extension method body is MessageBox.Show(text)
button.Click += text.ShowMessageBoxExtension; 
button.Click -= text.ShowMessageBoxExtension; // can you safely unsubscribe using delegate2?

var delegate1 = text.ShowMessageBoxExtension; 
var delegate2 = text.ShowMessageBoxExtension;
Debug.Assert(delegate1 == delegate2); // or more precisely is this always true?
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
wondra
  • 3,271
  • 3
  • 29
  • 48

1 Answers1

1

It's rathre question about references, delegate is just an object representing method. So it all comes down to equality of references, see code below presenting the problem:

// Here we are creating anonymous functions with lambdas,
// every time we create different object.
Action d1 = () => Console.WriteLine("");
Action d2 = () => Console.WriteLine("");
d1==d2;
// false
// Here we use already defined method, one object represenitng the method.
d1 = Console.WriteLine;
d2 = Console.WriteLine;
d1 == d2;
// true
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • So if I understand Jon Skeet's answer correctly both `d1` and `d2` can refer to same method due to optimaztion (complier emitted just one method, or it can choose to emit two methods). While compiler has no say in that matter when it comes to extension methods because they are alread defined somewhere (as member of some class). – wondra Nov 12 '19 at 11:00