Tuesday, 10 July 2012

Delegate Part 1

In this article, I  will explain delegates and their usage with the help of simple C# programs.
What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.


  1.     Encapsulating the method's call from caller
  2.     Effective use of delegate improves the performance of application
  3.     Used to call a method asynchronously


 public delegate void mydelegate();

//Program  using System;

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

namespace Delegates
    public delegate int mydelegate(int a, int b);
    class Program
        static int fn_Prodvalues(int val1, int val2)
            return val1 + val2;
        static void Main(string[] args)

            //Creating the Delegate Instance

            mydelegate delObj = new mydelegate(fn_Prodvalues);

            Console.Write("Please Enter Values");
            int v1 = Int32.Parse(Console.ReadLine());
            int v2 = Int32.Parse(Console.ReadLine());

           //use a delegate for processing

            int res = delObj(v1, v2);

            Console.WriteLine("Result :" + res);


Enter Two Values 5
Result : 7


    You can use delegates without parameters or with parameter list
    You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Here I have used a small program which demonstrates the use of delegate.

The delegate "mydelegate" is declared with double return type and accepts only two integer parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

mydelegate delObj = new mydelegate(int a , int b);

After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:


Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.