On button1_click one messagebox after another appear – first showing 30 the second showing 200:
public partial class Form1 : Form
{
delegate void myMathFunction(int j, int q);
void add(int x, int y) {MessageBox.Show((x + y).ToString());}
void multiply(int x, int y){MessageBox.Show((x*y).ToString());}
private void button1_Click(object sender, EventArgs e)
{
myMathFunction foo = new myMathFunction(add);
foo+= new myMathFunction(multiply);
foo.Invoke(10, 20);
}
public Form1() { InitializeComponent(); }
}
but the following just goes straight to the 200 and yet I’ve assigned both methods to the delegate – what has happened to add and why does it choose to use multiply?
public partial class Form1 : Form
{
delegate int myMathFunction(int j, int q);
int add(int x, int y){return x + y;}
int multiply(int x, int y) {return x * y;}
private void button1_Click(object sender, EventArgs e)
{
myMathFunction foo = new myMathFunction(add);
foo += new myMathFunction(multiply);
MessageBox.Show(foo.Invoke(10, 20).ToString());
}
public Form1() { InitializeComponent(); }
}
Can the second code sample be amended so that the delegate runs the add method rather than the multiply method?
When your delegate has multiple functions attached to it, each one is invoked in turn. If the delegate has a non-void return value, the return value of the last function is what is returned.
The language specification, 15.4 Delegate invocation, says
So, when you call
foo.Invoke(10, 20), the following happens:add(10, 20)is called which returns 30.multiply(10, 20)is called which returns 200 and that value is returned to the original caller.In your follow-up question you ask
As explained above, the
addmethod and themultiplymethod are both executed. The return value from the last executed method is what is returned to the caller. So, if you want the value resulting from callingaddto be returned, it must be the last method added to the delegate instance.