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?
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?
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):
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;
}