Delegates:
Definintion:
Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.
Using delegates basically includes three stages:1) Defining Delegate.
2) Declaring Delegate.
3) Method Definition.
These stages are elaborated as follows:
1) Defining Delegate:
public delegate double AddNumbers(double num1, double num2);While defining delegate, we are supposed to provide the parameters and the datatype of the delegate. In our example , the delegate has two parameters num1 and num2 which are of double type . And also the return type of our delegate is double.
2) Declaring Delegate:
Now after defining delegate, we need to declare our delegate .
public AddNumbers objAdd = null;I have created this object of our delegate and instantiated it to null. So that I can use it anytime in my code file without declaring it again and again.
3) Method Definition:
Now the final thing that we need to do is to create the method that is going to be referenced by our delegate.
So here is our method :
public double AddMyValues(double val1, double val2) { return val1+val2; }
Now, how we are going to integrate all these , is described below:
public delegate double Delegate_Add(double a,double b);
class MainClass {
static double AddMyValues(double val1, double val2) { return val1+val2; }
static void Main(string[] args){ //Creating the Delegate Instance Delegate_Add delObj = new Delegate_Add(AddMyValues); Console.Write("Please Enter Values"); double v1 = convert.toDouble(Console.ReadLine());
double v2 = convert.toDouble(Console.ReadLine());
double result = delObj(v1,v2);
Console.WriteLine ("Sum of two numbers is :"+result); Console.ReadLine();
}
}
Advantages of using delegates :
Thus , by using delegates we can increase perfomance of our application.1)Encapsulating the method's call.
2)Use of delegates improve the performance of application.3)Used to call a method asynchronously.
Happy Coding!
No comments:
Post a Comment