What's Delegate?

What's Delegate?

Delegate:- delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.
when you want to create a delegate in C# you make use of delegate keyword.
A delegate type maintains three important pices of information :

   1. The name of the method on which it make calls.
   2. Any argument (if any) of this method.
   3. The return value (if any) of this method.
 signature of delegate:-
Access modifier delegate returntype delegatename (passing value must be same as a function );
 public delegate int DelegateName(int x, int y);
Example:-


 namespace MyFirstDelegate

{

  public delegate int MyDelegate(int x, int y);

  public class MyClass

    {

        public static int Add(int x, int y)

        {

            return x + y;

        }

        public static int Mul(int x, int y)

        {

            return x * y;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

           MyDelegate del1 = new MyDelegate(MyClass.Add);

        int addResult = del1(5, 5);

            Console.WriteLine("5 + 5 = {0}\n", addResult);
  MyDelegate del2 = new MyDelegate(MyClass.Mul);
       int multiplyResult = del2(5, 5);

            Console.WriteLine("5 X 5 = {0}", multiplyResult);

            Console.ReadLine();

        }

    }
}


By:kamal
Date:2012-10-10 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related C Links

C interview questions and answers for experienced and fresher