Question

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?

Was it helpful?

Solution

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

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top