user2884789
user2884789

Reputation: 533

Delegate Method Property

I made a simple delegate example to try to understand delegates. Here is the code:

namespace DelegateExample
{

public delegate int BinaryOp(int x, int y);

public class SimpleMath
{
    public static int Add(int x, int y) { return x + y; }
    public static int Subtract(int x, int y) { return x - y; }
    public static int Multiply(int x, int y) { return x * y; }
    public static int Divide(int x, int y) { return x / y; }
}

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("*******Simple Delegate Example************");

        BinaryOp d = new BinaryOp(SimpleMath.Multiply);
        d += SimpleMath.Divide;
        d += SimpleMath.Add;

        Display(d);

        Console.ReadLine();
    }

    public static void Display(Delegate dobj)
    {
        foreach (BinaryOp del in dobj.GetInvocationList())
        {
            int ans = del.Invoke(10, 10);
            Console.WriteLine(ans);
            Console.WriteLine("Method Name: {0}", dobj.Method);              
        }
        Console.WriteLine("+++++++++++++++++++++++++++++++++++");
    }
}
}

and here is the output:

*******Simple Delegate Example*********
100
Method Name: Int32 Add(Int32, Int32)
1
Method Name: Int32 Add(Int32, Int32)
20
Method Name: Int32 Add(Int32, Int32)
+++++++++++++++++++++++++++++++++++ 

My Question: In the output, why does the .Method property return the same Name ('Add' in each case), yet the actual result returned is that of calling Multiply, Divide then Add?

Upvotes: 0

Views: 268

Answers (1)

LeffeBrune
LeffeBrune

Reputation: 3477

Because you made a type in your Display method:

Console.WriteLine("Method Name: {0}", dobj.Method);              

When it should be:

Console.WriteLine("Method Name: {0}", del.Method);              

Upvotes: 1

Related Questions