Sunday, April 5, 2015

Multicast Delegates

Multicast Delegates

1.A multicast delegate is a delegate that has references to more than one function.

2.When a multicat delegate is invoked,all the functions the delegate is pointing to, get invoked.

3.There are two approaches to create a multicast delegate:

    + or += to register a method with the delegate
    - or -= to un-register a method with the delegate

Example:

public delegate void SampleDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            SampleDelegate del1, del2, del3, del4;
            del1 = new SampleDelegate(SampleMethod1);
            del2 = new SampleDelegate(SampleMethod2);
            del3 = new SampleDelegate(SampleMethod3);

            del4 = del1 + del2 + del3;
            del4();

            //another way
            Console.WriteLine();
            Console.WriteLine("another way");
            Console.WriteLine();
            SampleDelegate del = new SampleDelegate(SampleMethod1);
            del += SampleMethod2;
            del += SampleMethod3;

            //del -= SampleMethod1;

            del();

            Console.Read();
        }

        public static void SampleMethod1()
        {
            Console.WriteLine("Sample Method 1");
        }

        public static void SampleMethod2()
        {
            Console.WriteLine("Sample Method 2");
        }

        public static void SampleMethod3()
        {
            Console.WriteLine("Sample Method 3");
        }
    }

No comments:

Post a Comment