Kjara Kjara - 1 year ago 61
C# Question

Are all methods in a delegate treated equally or are some of them special?

I recently learned that a delegate is not a pointer to ONE function, but to a LIST of functions (called "invocation list"). I would like to know if there is any difference between the methods in the list: Is one of them, or are several of them, somehow special? Are some of them stored somewhere else than in the invocation list?

I ask because I found a property

in the MSDN documentation (https://msdn.microsoft.com/en-us/library/system.delegate.method(v=vs.110).aspx) where it says

Delegate.Method Property:

Gets the method represented by the delegate.

Assuming that all methods stored in the delegate are treated equally, it is not clear to me WHICH method they mean. Most probably they mean the first one, but this is just a guess. Anyone out there who knows?

Answer Source

Just tested it:

public class Program
    public delegate int Opeartion(int x, int y);

    public static int Add(int x, int y)
        return x+y;

    public static int Sub(int x, int y)
        return x-y;

    public static void Main()
        Opeartion o = new Opeartion(Add);
        o += Sub;

And the output is the last assigned method:

Int32 Sub(Int32, Int32)

Even though Method property will return the last method it does not treat it differently and it is not speical over other other methods(except the fact that this is the last method that was added to the delagate and according to @Dennies_E commenet if the delegate return any value it will be the last method return value, in this case Sub method return value).

If you want to see all the assigend methods you can use Delegate.GetInvocationList method:

foreach(Opeartion operation in o.GetInvocationList())

This will print all the methods in the order they were added:

Int32 Add(Int32, Int32)

Int32 Sub(Int32, Int32)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download