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

前端 未结 11 2149
夕颜
夕颜 2020-12-05 23:30

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?

11条回答
  •  无人及你
    2020-12-06 00:16

    You can't do this because the delegate that handles the event is expecting a certain signature (you'll get compile error if you try and change it). For example the delegate in this case (Button.Click) is a System.EventHandler, it has to match that signature to compile/function as a delegate at all:

    public delegate void EventHandler(Object sender, EventArgs e)
    

    This is just how delegates work, when you look at how it's usually used, it makes more sense:

    MyButton.Click += button1_Click;
    

    If you returned anything else...what would it be used for? If you intend to call something that returns a result...that's what a method is for, not an EventHandler :)

提交回复
热议问题