Multi Cast Delegate Example



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Program for MULTI Cast Delegate
namespace CADelegates
{
    class ClsArithematic
    {
        public void Add(int X, int Y)
        {
            Console.WriteLine("Sum is        :-   " + (X + Y));
        }
        public void Subtract(int X, int Y)
        {
            Console.WriteLine("Difference is :-   " + (X - Y));
        }
        public void Multiply(int X, int Y)
        {
            Console.WriteLine("Product is    :-   " + (X * Y));
        }
        public void Divide(int X, int Y)
        {
            Console.WriteLine("Quotient is   :-   " + (X / Y));
        }
    }
    public delegate void MCDelegate(int a, int b);
    class ClsMCDelegate
    {
        static void Main()
        {
            ClsArithematic Obj1 = new ClsArithematic();
            MCDelegate ObjD = new MCDelegate(Obj1.Multiply);
            ObjD += Obj1.Add;
            ObjD += Obj1.Subtract;
            ObjD += Obj1.Divide;
            ObjD(44, 9);
            ObjD -= Obj1.Add;
            ObjD -= Obj1.Divide;
            ObjD(39, 1);
            Console.Read();
        }
    }
}




Output :-



  • To add reference of more functions to a delegate object, use+=operator like…,

         objD + = obj1.subtract;
         objD + = obj1.Add;

  • To delete the reference of any function from Delegate object use-=operator like…,

       objD - = obj1.subtract;
       objD - = obj1.Add;

No comments:

Post a Comment