Monday, June 03, 2013

Delegate

Posted by Rahul Kharde at 9:59 PM

A delegate is a type safe function pointer. Using delegates you can pass methods as parameters.
  • To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. That’s why delegates are called type safe function pointers.
  • Delegates are mainly used to define call back methods.
  • Effective use of delegate improves the performance of application
  • Delegates can be chained together; for example, multiple methods can be called on a single event.   
  • Delegates supports Events
  • Delegates give your program a way to execute methods without having to know precisely what those methods are at compile time
  • You can use delegates with or without parameters
Example

    public partial class _Default : System.Web.UI.Page
    {
        public delegate int Add(int i,int j);

        protected void Page_Load(object sender, EventArgs e)
        {
            Add objadd = new Add(MethodAdd);
            int Sum=objadd(10,20);
            Response.Write("Addition =" + Sum);
        }

        protected int MethodAdd(int i,int j)
        {
            return i + j;
        }       
    }

Output
  
Addition = 30


Multicasting of a Delegate

Multicast delegate means delegate which holds the reference of more than one method.
  • Multicast delegates Call the object of the delegates automatically call all method referred to this delegate. These methods can be attached and detached using "+=" and "-=" to the instance of the delegate.       

Example

public partial class _Default : System.Web.UI.Page
{
        public delegate int Add(int i,int j);

        protected void Page_Load(object sender, EventArgs e)
        {
            Add objadd = new Add(MethodAdd);           
            int Sum=objadd(10,20);
            Response.Write("<br/>Addition =" + Sum);

            objadd -= new Add(MethodAdd);
            objadd += new Add(MethodSubtract);

            int Subtract = objadd(20, 10);
            Response.Write("<br/>Subtract =" + Subtract);
        }

        protected int MethodAdd(int i,int j)
        {
            return i + j;
        }

        protected int MethodSubtract(int i, int j)
        {
            return i - j;
        } 
}

output

Addition = 30
Subtract = 10




If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top