Multicast delegate returning value – .Net C#

As we use multicast delegates to have multiple function get called as soon as delegate is called upon. In good practice, we call these kinds of delegates in case functions not returning any value; if there are then we should make use of multicast events in place of delegates calling the functions.

But if we require calling multicast delegate for the functions returning non void values, then output obtained from calling upon the delegate would be of the last call made i.e. of the last delegate added to the multicast delegate. It means values returned from the functions would be overwritten by the last function being called.

    public class MYTest

    {

        public int i;

        public string name;

        public delegate int TestDelegate(int value);

 

 

        public MYTest(int iValue, string nameValue)

        {

            i = iValue;

            name = nameValue;

        }

    }

    class Program

    {

        static int DelTestFunction1(int value)

        {

            return value++;

        }

 

        static int DelTestFunction2(int value)

        {

            return value+10;

        }

 

        static int DelTestFunction3(int value)

        {

            return value+20;

        }

 

        static void Main(string[] args)

        { 

           Console.WriteLine(“Multicast Delegate….!”);

MYTest.TestDelegate testDel = new MYTest.TestDelegate(DelTestFunction1);

           testDel += new MYTest.TestDelegate(DelTestFunction2);

           testDel += new MYTest.TestDelegate(DelTestFunction3);

 

           int delResult = testDel(10);

 Console.WriteLine(“Result obtained from multicast delegates: “ + delResult);

           Console.ReadLine();

  }

    }

Result:   30

Which is the value returned from the last function “DelTestFunction3”.

Advertisements
This entry was posted in .Net 2.0. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s