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.

// Draw the indicated function.
private void DrawGraph(FofXY func)
{
...
}

The DrawGraph method uses the following code to invoke PlotFunction. Notice how it passes the delegate variable func into PlotFunction.

PlotFunction(gr, func, -8, -8, 8, 8, dx, dy);

PlotFunction's declaration includes a delegate parameter much as DrawGraph's declaration does.

// Plot a function.
private void PlotFunction(Graphics gr, FofXY func,
float xmin, float ymin, float xmax, float ymax,
float dx, float dy)
{
...
}

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.

private void radF2_CheckedChanged(object sender, EventArgs e)
{
DrawGraph(F2);
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.