3

My (admittedly shaky) understanding is that you should be able to add any number of delegates to a C# event, and they all get invoked (in some undefined order). But that does not appear to be the case in my project. I've got it boiled down to two delegates added to the Activated event of an NSButton (this is in MonoMac), like so:

nsButton = new NSButton(new System.Drawing.RectangleF(0, 0, 100, 100));
nsButton.StringValue = "Click me!";

nsButton.Activated += delegate(object sender, EventArgs e) {
    Console.WriteLine("Handler 1!");
};
nsButton.Activated += delegate(object sender, EventArgs e) {
    Console.WriteLine("Handler 2?");
};

(and then this button gets added to a window, of course). When I click it, I see "Handler 1!" but I do not see "Handler 2?" appear in the Console. If I comment out the lines that add handler 1, then handler 2 fires.

It is behaving exactly as if only the first delegate added works, and any subsequent ones are ignored. But this defies everything I can find about how events in C# are supposed to work. What am I doing wrong?

csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63
Joe Strout
  • 2,634
  • 2
  • 28
  • 39
  • Consider looking at the source (assuming you can get one or use something like ILSpy to decompile) - as Servy(+1) answer points out you described default behavior which not necessary to be used by control. – Alexei Levenkov May 02 '14 at 16:26
  • Yes, I've been googling for the source, but haven't found it yet. I suspect that it is indeed something peculiar to NSButton, because virtually the same code hooked up to a UIButton's TouchUpInside event on iOS works fine. – Joe Strout May 02 '14 at 16:47
  • With some help from Xamarin, I've managed to update from MonoMac to Xamarin.Mac. But this behavior is the same. Still haven't managed to find any official word or documentation about whether this is intended behavior. – Joe Strout May 08 '14 at 18:08

2 Answers2

1

It's worth noting that you have described how events should behave, not how they must behave. The type defining the event can ignore those guidelines if it wants to, and not hold onto more than one handler. That is not the behavior that you'll see of almost all events though, as they would have had to go out of their way to generate that behavior.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

This in fact is a bug. I filed it here:

https://bugzilla.xamarin.com/show_bug.cgi?id=19619

chamons
  • 36
  • 3