1

I need to convert string to executable code. The string is in foreach statement.

foreach (InsuredItem _i in p.InsuredItems)
{
    string formula = "(_i.PremiumRate/100)*SumAssured";
    _i.Premium = (Execute formula);
}

The formula is loaded from setup. this is just a demonstration. I need to execute the string in foreach loop. Thanks.

1 Answers1

5

Assuming that your formula is valid C# code and that it uses a known set of local variables (so that you can create a "globals" type containing all of them), you should be able to use Roslyn scripting API to do this:

public class Globals
{
    public InsuredItem _i;
    public decimal SumAssured;
}

…

string formula = "(_i.PremiumRate/100)*SumAssured";
var script = CSharpScript.Create<decimal>(formula, globalsType: typeof(Globals))
    .CreateDelegate();

foreach (InsuredItem _i in p.InsuredItems)
{
    _i.Premium = await script(new Globals { _i = _i, SumAssured = SumAssured });
}
svick
  • 236,525
  • 50
  • 385
  • 514
  • BTW, having local variable names start with underscore is unusual in C#, you might want to consider using common naming conventions. – svick Mar 24 '17 at 15:11
  • Am getting 'The name 'VVC' does not exist in the current context' at var script = CSharpScript.Create(formula, globalsType: typeof(Globals)) .CreateDelegate(); – Sebastian Kilonzo Mar 27 '17 at 10:15
  • @SebastianKilonzo Well, what is VVC? It has to be something specific to your code. Is it something in the formula? – svick Mar 27 '17 at 10:25
  • Thanks svic... you are right, it was something with my variables. Its now working – Sebastian Kilonzo Mar 27 '17 at 11:21