Can Roslyn used to evaluate a dynamic if in c#
-
Saturday, March 24, 2012 2:51 AM
I asked this question in stack over flow at
One of the suggestion was to use Rosyln. In my case I will have a code like the following
if (15 > 10)
{
return 45;
}
else
{
int result = 23 + 20;
return result;
}
all variables evaluated to a values. I would like to evaluate the expression and get the result. Is it possible to do with Rosyln?
All Replies
-
Saturday, March 24, 2012 2:28 PM
If you're creating the code, then maybe producing it as a string is not the best idea. I think it would be better if the result was a Expression or Roslyn SyntaxNode. But if you're sure you want to use strings, then, yes, you can compile and execute it using Roslyn.
Probably the best option is to use the Scripting API. Although your code is in quite a weird format: it looks like a method body without the method, it's certainly not an expression. One way to work around that is to enclose your code in a lambda and execute that:
var engine = new ScriptEngine(); Func<int> func = engine.Execute<Func<int>>("() => { " + yourCode + " }"); int result = func();- Edited by svick Saturday, March 24, 2012 2:28 PM

