3

I need a function to evaluate the value of a string as C# code. The string contains local variables and arithmetic operations, and the function works as if the string is the code in the same place. Something like:

int a = ...; int b = ...; int c = ...;
...
int result = Eval("a+b+c"); // should return current value a+b+c

We can limit the discussion to the simple types like int and arithmetic operations between them. Is it possible to do that in C#/.Net? It is acceptable to pass in context parameter to the function, say, containing the name and value of all required variables.

Thanks!

Yang Zhao
  • 315
  • 1
  • 5
  • Could you take a look at DataTable.Compute method. – Gagan Deep Jun 15 '20 at 06:25
  • 1
    https://stackoverflow.com/questions/1207809/evalstring-to-c-sharp-code there is a link to a nice project Eval Expression.NET – Falco Alexander Jun 15 '20 at 06:26
  • You can't really call `Eval("a+b+c")` method without passing local variables into it too, unless this is some kind of code injection instead of method call. If you are able to create environment, then codedom is easy way: just create a long string, contatining class definition and fields with local variable values and wrap equation into a method call. Compile in memory, run, done. – Sinatr Jun 15 '20 at 06:32
  • see this link: https://stackoverflow.com/q/333737/9681220 – Taher Fattahi Jun 15 '20 at 06:35

1 Answers1

-1

Prepend script that declares and initializes the variables. For example, if you wish to pass a variable named a into the script, do this:

var script = string.Format("var a = {0}\r\n", a) + script;
var result = Eval(script);
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • 2
    what is Eval()?? – Falco Alexander Jun 15 '20 at 06:41
  • Maybe I misunderstood the question. I thought OP was asking this: Given the ability to compile and execute a string containing c# code, how can the program pass in local variables?" – John Wu Jun 15 '20 at 06:46
  • *"I need a function"* - said OP. Since you don't know what is `Eval()`, why do you think it supports what you suggest as the answer? – Sinatr Jun 15 '20 at 07:25
  • I assumed that `Eval()` was a placeholder for a compilation function, sort of as if the OP were using `Foo()` but with a more representative name. As I said, i may have misunderstood the question. – John Wu Jun 15 '20 at 07:29