#1,021 – What Happens to a Delegate’s Return Value

The return value from a delegate instance is passed back to the caller.  For example:

        private delegate int ReturnIntDelegate();

        static int Method1()
        {
            return 12;
        }

        static void Main(string[] args)
        {
            ReturnIntDelegate del1 = Method1;

            // Invoke
            int val = del1();
            Console.WriteLine(val);
        }

1021-001

Recall, however, that a delegate instance can refer to more than one method.  When a caller invokes a delegate whose invocation list contains more than one method, the value returned to the caller is the return value of the last delegate instance in the invocation list.  Return values of other methods in the invocation list are lost.

        static int Method1()
        {
            return 12;
        }

        static int Method2()
        {
            return 99;
        }

        static void Main(string[] args)
        {
            ReturnIntDelegate del1 = Method1;
            del1 += Method2;

            // Invoke
            int val = del1();
            Console.WriteLine(val);
        }

1021-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #1,021 – What Happens to a Delegate’s Return Value

  1. Thanks Sean. Learning something new every single day 🙂

  2. Pingback: #1,022 – How to Use Return Values from All Delegate Instances | 2,000 Things You Should Know About C#

Leave a comment