Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to use delegate can anyone suggest some example...
Thank you....
Posted

Delegates are roughly similar to function pointers in C++.
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature and can be used later.

How to use

The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration.

See the fallowing program for more information on using delegates.

C#
 namespace delegatess
{
    //Create a new category
    public delegate int MyDelegate(int x, int y);
    public class MyDelegateProgram
    {
        public static int FunAdd(int x, int y)
        {
            return x + y;
        }

        public static int FunMultiply(int x, int y)
        {
            return x * y;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //instance and initialization
            MyDelegate DelAdd = new MyDelegate(MyDelegateProgram.FunAdd);
            MyDelegate DelMul = new MyDelegate(MyDelegateProgram.FunMultiply);

            //invoking function using delegates
            Console.WriteLine("Addition : " + DelAdd(4, 5));
            Console.WriteLine("Multiplication : " + DelMul(4, 5));

            //array of Delegates-----------
            Console.WriteLine("Using Array of Delegate");

            MyDelegate[] arrDelegates;
            arrDelegates = new MyDelegate[2]; //size of delegate array
            arrDelegates[0] = new MyDelegate(MyDelegateProgram.FunAdd);
            arrDelegates[1] = new MyDelegate(MyDelegateProgram.FunMultiply);

            foreach (MyDelegate item in arrDelegates)
            {
                Console.WriteLine(item(4, 5));
            }
            Console.ReadKey();
        }
    }
}

Hope this helps
 
Share this answer
 
Delegate is defined with a specific signature. To invoke a delegate object,methods are required with the same signature.
See for more details.this may help you:Delegate example
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900