Delegate is different from normal method.Delegate is a type which holds method reference in an object.It is also called as type safe function pointer.It is similar to C++ pointer.But the difference is c++ pointers are not type safe.It can point to any type of method.but delegate is type safe.we cannot point int type delegate to a string type.
A delegate should have the same signature and same number of parameters as that of a method to encapsulate the method or to create a reference for that method.
public delegate int Delegate_Sum(int a,int b); //This is a delegate which refers to the method "Sum".Observe that the delagate has same signature and same number of parameters as that of method.
static int Sum(int val1,int val2)
static void Main(string args)
Delegate_Sum delObj = new Delegate_Sum(Sum); //Creating a delegate instance and passing the parameter as Method Name
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); //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.
Console.WriteLine ("Result :"+res);
Some of the advantages of Delagates are:-
1.It encapsulates the method call
2.It increases the performance of the application
3.We can call a method Asynchronously using a delegate.We have multicast delegates as well...
Rajasekhar0544, if this helps please login to Mark As Answer. | Alert Moderator