views:

394

answers:

2

If I have an event whose handler returns a bool, what happens if I attach multiple events??

see this example

public class MyClass
{
 public delegate bool MyEventHandler(object sender, EventArgs e);
 public event MyEventHandler Submit;

 public void DoSubmissions()
 {
  if (Submit != null && Submit(this, null))
  {
   Console.Write("HOORAY");
  }
 }
}

so in my example, the handler returns true on a successful submission. but i assign two handlers to the event...what happens? the first handler's return is used? the 2nd? neither? both?

+2  A: 

the return value of the last event to be registered is used.

John Weldon
+2  A: 

In general, that's a bad design.

Consider using a pattern like CancelEventArgs where you embed the return value in the EventArgs. That lets future handlers inspect and/or change the value. A ref would work the same, as it'd be passed from handler to handler, but is a little bit unexpected IMO:

When the signature includes a parameter that is passed by reference, the final value of the parameter is the result of every method in the invocation list executing sequentially and updating the parameter's value.

But, yeah - in your example, it's the last handler called:

When the signature of the methods invoked by a delegate includes a return value, the delegate returns the return value of the last element in the invocation list.

which is guaranteed to be in the order that they were added:

the result of the [addition] operation is a new delegate instance that, when invoked, invokes the first operand and then invokes the second operand

But, since no handler knows if it's first, middle, or last - it seems useless to me.

Mark Brackett