15,938,218 members
See more:
I have a programs with thousands of variables. I need to perform complex operations on each of these variables that involves other variables.

Some of the formulas that I will using will call methods that I have defined. So the string for z may be "x + y", but it might also be "NewMethod(x,y)"

What I would like to do is create a two column spreadsheet containing each of the variable names and the formula (stored as a string) used to calculate that variable's value. For each variable in the C# program, I would look up the string containing the formula and then calculate that formula.

Simple example:

Let's assume that there are three variables: x, y, and z.
x = 10
y = 20

I look up the formula for z and it returns the following string:
string = "x + y"

I am looking for a function that would do the equivalent of:
z = eval(string)
such that z would equal 30.

How can I do this in C#?

Many thanks in advance for any help.
Posted

## Solution 3

Hi,
As I know there is no equivalent for eval (like vb6) in c#. but you can use system.CodeDom.Compiler namespace to create your own eval function. by using that you can compile your code on the fly and use it in your program.

Spenser723 14-Sep-10 0:16am
Thank you, Aidin. I will look into that.
Let me know if you had any question.I had the same problems before.

## Solution 2

Thanks for your response. Not sure that operator overloading would help in this case. That would be good if I wanted to perform standard operations on a new class object.

In my case, what I want to do is the following:

Let's assume that we have a program with the following variables:

```double x1 = 20;<br />
double x2 = 30;<br />
double y = 100;<br />
string s = "y + NewMethod(x1, x2)";```

Furthermore, let's assume that NewMethod() is some method that performs a calculation on its two parameters and returns a value of type double. For example, let's assume that NewMethod(20,30) would produce 610.23 as a result.

I am looking for a method (let's call it "Formula()" for demonstation purposes), such that:

`z = Formula(s);`

would produce the same result as:

`z = y + NewMethod(x1, x2);`

(i.e. z would be equal to 710.23)