Tuesday 12 March 2013

Types of Delegates

Delegates are of two types:
  • Unicast Delegate
  • Multicast Delegate
If a delegate is used for calling a single method we call it as a unicast delegate whereas if a delegate is use for calling multiple methods its a multicast delegate.
In case of the methods delegate, a single delegate call will execute all the methods that are bound with the delegate.
using System;

namespace CSharpConsole
{
    public  delegate void MathDel(int x, int y);
    class DelMulti
    {
        public void Add(int x, int y)
        {
            Console.WriteLine("Add:  " + (x + y));
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine("Sub:  " + (x - y));
        }
        public void Mul(int x, int y)
        {
            Console.WriteLine("mul:  " + (x * y));
        }
        public void Div(int x, int y)
        {
            Console.WriteLine("Div:  " + (x / y));
        }
        static void Main()
        {
            DelMulti obj = new DelMulti();
            MathDel md=new MathDel (obj.Add );
            md+=obj.Sub ;md +=obj.Mul ;md +=obj.Div ;
            md(100,25);
            Console .WriteLine ();
            md(600,30);
            Console .WriteLine ();
            md -=obj.Mul ;
            md(450,50);
            Console .ReadLine ();
            
        }

    }
}
 

 

No comments:

Post a Comment