Delegates explained
By rickvdbosch
- 2 minutes read - 379 wordsDelegates can be seen as interfaces for methods. Let’s look at an example of a delegate and what it really represents.
delegate double Calculation(double one, double two);
All this line of code really does, is tell the class it is in that there might be one or more methods with the given signature: a method returning a double and taking two doubles as parameters. You cannot call a method Calculation now, because it does not have a body, so it doesn’t have any functionality. It’s just a blueprint for future reference. You’re saying something like: “You might find one or more methods somewhere having this signature which do something for you, but don’t ask me where or what they are called. Just be ready!” Next, let us create a method with the same signature as the delegate.
static double Multiply(double first, double second)
{
return (double)(first * second);
}
This method has the same signature as the delegate. But, just for fun, let’s make another…
static double Divide(double A, double B)
{
return (double)(A / B);
}
Notice that not only the names of the two methods are different, even the parameter names are not the same. The delegate doesn’t care: you have defined it for methods returning a double, and taking two doubles as parameters and that’s all that matters to the delegate. The delegate now lets you call either one of these methods using a new object of the delegate you declared:
Calculation calc = new Calculation([functionname]);
Substitute [functionname] with the name of the function you would like to use, and you are ready to go:
Calculation calc = new Calculation(Multiply);
double answer = calc(50, 4);
Result for answer here is 200.
or
Calculation calc = new Calculation(Divide);
double answer = calc(50, 4);
Result for answer here is 12.5.
Because the delegate was created stating it had to return a double and would take two doubles as parameters, it’s enough to pass the method name to the creator of the new delegate. This will only accept names of methods that have the right signature. Otherwise, you will get an error stating Method ‘method name’ does not match delegate ‘complete delegate statement’.
In my next post I will be showing how delegates can be used to create eventhandlers.