Sunday, January 20, 2013

How to retrieve values from multicast delegate in C#?


Retrieve values from multicast delegate

We use multicast delegate to have multiple methods and by single invoke, all the reference methods get called. This is a good practice for the functions those having return type 'void'. But if your functions return some value then there is a different way to get the return value.


Get last method return value

    public class Class1
    {
        public int Method1()
        {
            return 1;
        }
    }

    public class Class2
    {
        public int Method2()
        {
            return 2;
        }
    }

    public class Class3
    {
        public int Method3()
        {
            return 3;
        }
    }  


    public class Operatinos
    {
        public delegate int MyDelegate();
        MyDelegate objMyDelegate;

        Class1 objClass1 = null;
        Class2 objClass2 = null;
        Class3 objClass3 = null;

        //Constructor
        public Operatinos()
        {
            objClass1 = new Class1();
            objClass2 = new Class2();
            objClass3 = new Class3();


            objMyDelegate += objClass1.Method1;
            objMyDelegate += objClass2.Method2;
            objMyDelegate += objClass3.Method3;
        }

        public void OperationFailed()
        {
            int i = objMyDelegate.Invoke();
            Console.WriteLine(“Return value :- “ + i.ToString());

        }
    }

    public class MulticastDelegateReturnValue
    {
        static void Main()
        {
            Operatinos op = new Operatinos();
            op.OperationFailed();

            Console.ReadLine();
        }
    }

Output

Return value :- 3


Get all method return value

Use above sample and only modify the operation class to get the all function return value.

    public class Operatinos
    {
        public delegate int MyDelegate();
        MyDelegate objMyDelegate;

        Class1 objClass1 = null;
        Class2 objClass2 = null;
        Class3 objClass3 = null;

        //Constructor
        public Operatinos()
        {
            objClass1 = new Class1();
            objClass2 = new Class2();
            objClass3 = new Class3();


            objMyDelegate += objClass1.Method1;
            objMyDelegate += objClass2.Method2;
            objMyDelegate += objClass3.Method3;
        }

        public void OperationFailed()
        {
            foreach (MyDelegate del in objMyDelegate.GetInvocationList())
            {
                int i = del();

                Console.WriteLine("Return value :-" + i.ToString());
            }
        }
    }
            

Output

Return value :- 1
Return value :- 2
Return value :- 3

No comments:

Post a Comment