2

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.

5
  • stackoverflow.com/questions/34758802/… Commented Mar 24, 2017 at 6:07
  • ncalc.codeplex.com Commented Mar 24, 2017 at 6:07
  • You want only formula or result? Commented Mar 24, 2017 at 6:09
  • I need the result. Which will be decimal value Commented Mar 24, 2017 at 6:47
  • Below is the code which i have tried but still not working: Expression ev = new Expression(formula); ev.Parameters["_i"] = _i; _i.Premium = ev.Evaluate().ToDecimal(); Commented Mar 24, 2017 at 7:07

1 Answer 1

7

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 });
}
Sign up to request clarification or add additional context in comments.

4 Comments

BTW, having local variable names start with underscore is unusual in C#, you might want to consider using common naming conventions.
Am getting 'The name 'VVC' does not exist in the current context' at var script = CSharpScript.Create<decimal>(formula, globalsType: typeof(Globals)) .CreateDelegate();
@SebastianKilonzo Well, what is VVC? It has to be something specific to your code. Is it something in the formula?
Thanks svic... you are right, it was something with my variables. Its now working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.