[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Graph equations entered by the user in C#

[Graph equations entered by the user in C#]

This example draws a graph of an equation entered by the user by combining techniques from the following two posts:

This example uses techniques from first post to compile the equation entered by the user. It takes the text entered by the user and builds a C# class similar to the following.

using System; public static class Evaluator { public static double Evaluate(double x) { return (1 / x + 1 / (x + 1) - 2 * x * x) / 10; } }

The program then compiles this code and gets a MethodInfo object representing the Evaluator class's Evaluate method.

Next the program loops through X values to draw the graph as done in the second post listed above. It uses the MethodInfo object's Invoke method to call the Evaluate function for the different X values and uses the results to draw the graph.

The only really new thing to notice here is that you only need to compile the function once and then you can invoke it many times to draw the graph. That's important because compiling the function takes a bit of time so recompiling every time you needed to evaluate the function would be relatively time consuming.

Note that you must capitalize Math library methods correctly to make a graph. For example, to use the sine function you must spell if Math.Sin as shown in the picture at the top of the post. Also note that the looping variable x must be in lower case within the graph equation.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.