Why do event handlers always have a return type of void?

Viewed 23820

Hey, I wondered why is it that the return type of events such as

private void button1_Click(object sender, EventArgs e)

is always void?

Can it return any other value too?

11 Answers

introductory note: If the [single] method you want to call is on the same or lower dependency level as your calling code, then you can just go ahead and call it, there will be no need for events. So; events are only useful when at least one of your event raises (calls) is going to call a method from a layer above.

Now, long answer depends on whether you write your own delegate and marking it as an event (1) or use EventHandler (2):

  1. If writing your own delegate, you could just have return the result you need. The problem though is that with multicast delegates only the result of the final subscribed method is returned.


    public class TestEvents
    {
        public event SomethingHappenedHandler1 SomethingHappened1;
        public event EventHandler SomethingHappened2;
    
        public void Run()
        {
            SomethingHappened1 += Scenario_DelegateOnly.SubscriberMethod;
            SomethingHappened1(this, 13, 15);
    
            SomethingHappened2 += Scenario_EventHandlerAndEventArgs.SubscriberMethod;
            SomethingHappened2(this, new MyEventArgs2(33, 35));
        }
    }
    
    //1
    public delegate int SomethingHappenedHandler1(object sender, int arg1, int arg2);
    public static class Scenario_DelegateCanHaveReturnValue
    {
        public static int SubscriberMethod(object sender, int arg1, int arg2)
        {
            Console.WriteLine($"{sender.ToString()} {arg1} {arg2} ... returning {arg1} * {arg2}");
            return arg1 * arg2;
        }
    }
    
    //2
    public static class Scenario_EventHandlerAndEventArgs
    {
        public static void SubscriberMethod(object sender, MyEventArgs2 args)
        {
            Console.WriteLine($"{sender.ToString()} {args.arg1} {args.arg2}");
        }
    }
    public class MyEventArgs2 : EventArgs
    {
        public MyEventArgs2(int arg1, int arg2)
        {
            this.arg1 = arg1;
            this.arg2 = arg2;
        }
        public int arg1;
        public int arg2;
    }

  1. If using EventHandler signature of your method return type will always be "void". Most often event raises are fire and forget operations (such as button_Click) and we might not care about results of operation, but when we do need some feedback, there is always a workaround because subscriber method can save those results to a property on the publisher; it just has to cast "sender" object to get an instance of publisher [which should be no problem unless subscriber is below the publisher in dependency (scenario noted where we did not need events to begin with!)].
Related