Sunday, December 28, 2014

Program to explain about Delegates

9:17 PM - By azeheruddin khan 0

Description: - A delegate is a user defined type like class which holds the reference (i.e. memory address) of a method in its reference variable. A delegate is used to call a method at run-time. In the below given program, we have a delegate: operate, which is a single-cast delegate as it refers to only one method at run-time. All single-cast delegates are derived from System.Delegate class. The reference assigned to a delegate can change at run-time.

In the below given program, the delegate:-

Public delegate void operation(int x,int y)

Accepts two arguments (a,b) and assigns it to its parameters ‘x’ and ‘y’. The values assigned to these parameters are passed to the method: addition( ) which has two parameters ‘a’ and ‘b’. The reference variable ‘p’ of the delegate: 'operate’ contains the reference of the method: ‘sum’. So, it is able to call the method indirectly and pass two values (a,b) as arguments to the method.      

The syntax for declaring a delegate is:-
Delegate <return type> delegate-name <parameter list>

The syntax for instantiating a delegate is:-
 Delegate-name delegateobject=new delegate-name(classobject.methodname) 


using System;

namespace DelegateExample
    class Program
        delegate void operate(int x, int y);
        static void Main(string[] args)
            Operation o = new Operation();
            operate p = new operate(o.sum);
            p(80, 90);


    public class Operation
        int c;
        public void sum(int a, int b)
            c = a + b;
            Console.WriteLine("The sum is " + c);



About the Author

I am Azeheruddin Khan having more than 6 year experience in c#, and ms sql.My work comprise of medium and enterprise level projects using and other Microsoft .net technologies. Please feel free to contact me for any queries via posting comments on my blog,i will try to reply as early as possible. Follow me @fresher2programmer
View all posts by admin →

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post



© 2014 Fresher2Programmer. WP Theme-junkie converted by Bloggertheme9
Powered by Blogger.
back to top