Peymon
Peymon

Reputation: 41

How to execute my string as code

I'm currently making a calculator. I know how to write the logic but I'm curious if it can be done the way I'm going to explain.

String str = "12 + 43 * (12 / 2)";
int answer;

answer = str.magic(); 

//str.magic is the same as 
answer =   12 + 43 * (12 / 2);

now what I want is how I can turn str into executible code.

Upvotes: 2

Views: 2638

Answers (2)

Fratyx
Fratyx

Reputation: 5797

You can use CodeDom to get a 'native' C# parser. (You should improve the error handling.)

using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

...

static void Main()
{
    double? result = Calculate("12 + 43 * (12 / 2)");
}

static double? Calculate(string formula)
{
    double result;
    try
    {
        CompilerParameters compilerParameters = new CompilerParameters
        {
            GenerateInMemory = true, 
            TreatWarningsAsErrors = false, 
            GenerateExecutable = false, 
        };

        string[] referencedAssemblies = { "System.dll" };
        compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);

        const string codeTemplate = "using System;public class Dynamic {{static public double Calculate(){{return {0};}}}}";
        string code = string.Format(codeTemplate, formula);

        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, new string[]{code});
        if (compilerResults.Errors.HasErrors)
            throw new Exception();

        Module module = compilerResults.CompiledAssembly.GetModules()[0];
        Type type = module.GetType("Dynamic");
        MethodInfo method = type.GetMethod("Calculate");

        result = (double)(method.Invoke(null, null));
    }
    catch (Exception)
    {
        return null;
    }

    return result;
}

Upvotes: 5

Darshan Faldu
Darshan Faldu

Reputation: 1605

You can simply use NCalc library Click here for more information. you can download that dll file from here

Example:

NCalc.Expression exp= new NCalc.Expression("(12*3)-29");
object obj = exp.Evaluate();
MessageBox.Show(obj.ToString());

Upvotes: 1

Related Questions