BLOG.CSHARPHELPER.COM: Use delegates to pass a method's address to another method in C#
Use delegates to pass a method's address to another method in C#
The example Plot the equation of a function of two variables in C# shows how to draw a graph of a function even if you don't really understand its shape ahead of time. That example's PlotFunction method invokes the function F1 to get values for the function to plot.
The PlotFunction method would be a lot more useful if it could plot lots of different functions. This example shows how you can use delegates to do just that.
A delegate is basically a pointer to a method. You can make a delegate type that indicates a specific type of method, such as one that takes two parameters and returns void, or one that takes no parameters and returns an int.
After you define a delegate type, you can create variables of that type, assign them to point to a particular method, and invoke them.
This example uses the following code to define a delegate type named FofXY. This represents a method that takes two float parameters and returns a float value.
// Define a delegate type named FofXY. private delegate float FofXY(float x, float y);
The program's DrawGraph method prepares a Bitmap to hold the graph and then calls PlotFunction to do the actual plotting. The following code shows DrawGraph's declaration. Notice the parameter of type FofXY.
PlotFunction uses code similar to the following to invoke the delegate that it is passed.
float last_y = func(x, ymin);
When you click the program's radio buttons, their event handlers invoke DrawGraph, passing it the appropriate function. For example, when you click the last radio button, the following code calls DrawGraph, passing it the method F2 to generate the result shown at the beginning of this entry.
Comments