Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Please refer my program to understand my question. Please dont guide me to msdn or any articles thank you

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delgates_Ex1
{

    public delegate void ExampleDelgate(int x, int y);


    class Democlass
    {
        public void Add(int x, int y)
        {

            Console.WriteLine(x+y);
            

        }


        public static void mul(int x, int y)
        {
            Console.WriteLine(x*y);

        }

    }


    class Program
    {
        public static void Sub(int x, int y)
        {

            Console.WriteLine(x -y);


        }



        static void Main(string[] args)
        {
            Democlass d = new Democlass();

            ExampleDelgate e1 = new ExampleDelgate(d.Add);  // I know here I am doing  instantiation of the delegate

            ExampleDelgate e2 = new ExampleDelgate(Democlass.mul);

            ExampleDelgate e3 = e1 + e2;


            e3 = e1 + e2 + e3;  // When I execute the line i get twice i.e out put would be  30 200 30 200 can any one explain me what is happening here. Basically I am trying to
            //understand Mutlicast delegates and when i remove +e3 i just get only once


            e3(20, 10);  // and here I am doing Delegate Invocation

        }
    }
}
Posted
Updated 30-May-14 5:02am
v2

1 solution

1. ExampleDelgate e3 = e1 + e2; create an delegate object e3 as sum of e1 and e2 this is similar with the adding into an "event" two methods, in this case the list will have the next 2 methods: Add and mul.

So if you will invoke e3(20, 10); ==> both methods Add(20, 10) and mul(20,10) will be executed. and you will have the results: 30 , 200

2. If you add the extra line: e3 = e1 + e2 + e3; this is equivalent with: e3+= e1 +e2; ==> the list of methods will become: Add , mul, Add , mul.

So if you will invoke e3(20, 10); ==> 4 methods will be executed ==> 30, 200, 30, 200
 
Share this answer
 
v2
Comments
RDBurmon 30-May-14 11:19am    
good explanation. My +5
Raul Iloc 30-May-14 11:27am    
Thank you for your vote!
RDBurmon 30-May-14 11:29am    
:)
ShaHam11 30-May-14 11:30am    
Thank you for clarifying. So basically e3 has the address of e1+ e2 and when invoked it gives the output and when we add another extra line e3 = e1 + e2 + e3 .. this will contain first executed output plus the new output
Raul Iloc 31-May-14 9:00am    
Something like this, but each add is in fact adding/registration of the method/methods into the current method list associated with the delegate.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900