7/26/2010

C# Multicast delegates



Multicast Delegate:
-------------------
A single delegate contains several methods in its invocation list is called multicast delegate.
Since a single delegate can return only one value at a time, the return type of the delegate declaration must be void because a delegate contains several methods in its invocation list.
To add a new method to the invocation list use +=
Example:
         mydel m1+=new mydel(arith_oper.add);
To remove a method from the invocation list use -=
Example:
         mydel m1-=new mydel(arith_oper.prod);      


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

namespace ConsoleApplication18
{
    class arith_oper
    {
        public static void add(int a, int b)
        {
            Console.WriteLine("Sum: " +(a + b));
        }

        public static void prod(int a, int b)
        {
            Console.WriteLine("Product: "+ (a * b));
        }

        public static void diff(int a, int b)
        {
            Console.WriteLine("Difference: " + (a - b));
        }
    }
    class Program
    {
        public  delegate void mydel(int a,int b);
        static void Main(string[] args)
        {
            mydel m1 = new mydel(arith_oper.add);

            m1 += new mydel(arith_oper.diff); 

            m1 += new mydel(arith_oper.prod);

            m1(6, 2);

            m1 -= new mydel(arith_oper.prod);
            m1(7, 3);
        }
    }
}

No comments:

Post a Comment