Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# delegate only writes out last method

I have this code:

public void myMethod()
{
    int a = 10;
    int b = 20;
    Func<int, int, int> multiplyDelegate;
    multiplyDelegate = Multiply;
    multiplyDelegate += Multiply2;

    Console.WriteLine(multiplyDelegate(a,b));
}

public int Multiply(int x, int y)
{
    return x * y;
}
public int Multiply2(int x, int y)
{
    return x * y + 10;
}

By running myMethod, I expect the console to show the returns from both methods "Multiply" and "Multiply2" but only the return from the method "Multiply2" is shown. Have I done something wrong here or have I misunderstood the concept of delegates? From what I've learned a delegate is an array of references to methods.

like image 372
Robin Cox Avatar asked Dec 02 '22 13:12

Robin Cox


1 Answers

From Using Delegates (C# Programming Guide):

If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked.

like image 58
Dmitry Egorov Avatar answered Dec 25 '22 00:12

Dmitry Egorov