0

I need to evaluate arithmetic expression with exponentiation from string, for example:

string expression = "4*5+2^3"

^ symbol could be change to any other symbol or string, but it have to be written in same way as + - * operations because numbers and operators are somewhat randomly generated. Is there a way to do it? I'm not sure you can write exponentiation operation this way in NCalc or Jace.Net

Dork
  • 1,816
  • 9
  • 29
  • 57
  • I don't see any simple solution. You have to tokenize the expression and then replace the `^` with `Math.Pow`... complex. – xanatos Jun 16 '17 at 07:38
  • It is complex to tokenize the expression because 5+(3+2)^(4+3) is "complex" (the brackets)... and it can become even more complex easily. – xanatos Jun 16 '17 at 08:24

1 Answers1

0

You can write Evaluator class as below to execute C# code dynamically:

public class Evaluator
{
    public int Evaluate(string expression)
    {
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CompilerParameters compilerParameters = new CompilerParameters();
        compilerParameters.ReferencedAssemblies.Add("system.dll");
        compilerParameters.CompilerOptions = "/t:library";
        compilerParameters.GenerateInMemory = true;

        StringBuilder typeDefinition = new StringBuilder("");
        typeDefinition.AppendLine("using System;");
        typeDefinition.AppendLine("namespace Evaluator");
        typeDefinition.AppendLine("{");
        typeDefinition.AppendLine("    public class Evaluator");
        typeDefinition.AppendLine("    {");
        typeDefinition.AppendLine("        public object Evaluate()");
        typeDefinition.AppendLine("        {");
        typeDefinition.AppendLine("            return " + expression + ";");
        typeDefinition.AppendLine("        }");
        typeDefinition.AppendLine("    }");
        typeDefinition.AppendLine("}");

        CompilerResults compilerResult = codeProvider.CompileAssemblyFromSource(compilerParameters, typeDefinition.ToString());

        System.Reflection.Assembly a = compilerResult.CompiledAssembly;
        object o = a.CreateInstance("Evaluator.Evaluator");
        Type dynamicEvaluatorType = o.GetType();
        MethodInfo dynamicEvaluateMethod = dynamicEvaluatorType.GetMethod("Evaluate");
        return (int) dynamicEvaluateMethod.Invoke(o, null);
    }
}

Then you can use it like that:

        string expression = "4*5+2";
        int result = new Evaluator().Evaluate(expression);
fdafadf
  • 809
  • 5
  • 13