1

I have the following declarations:

int value1 =5 , value2 =10 ,value3;     
string calculate ="value1 + value2"; // dynamic string

I need to perform

value3 = convert.To int32(calculate );

Is there any possible to compute dynamic variable assigning ...

Mamta D
  • 6,310
  • 3
  • 27
  • 41
Nagesh Hunter
  • 13
  • 1
  • 5

4 Answers4

1
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections.Generic;

static public class Sample {
    static public double eval(string exp, Dictionary<string,string> varlist){
        CSharpCodeProvider csCompiler = new CSharpCodeProvider();
        CompilerParameters compilerParameters = new CompilerParameters();
        compilerParameters.GenerateInMemory = true;
        compilerParameters.GenerateExecutable = false;
//      compilerParameters.ReferencedAssemblies.Add("System.dll");
        string temp =
@"static public class Eval {
    static public double calc() {
        double exp = $exp;
        return exp;
    }
}";
        string equation = exp;
        foreach(var key in varlist.Keys){
            equation = equation.Replace(key, varlist[key]);
        }
        temp = temp.Replace("$exp", equation);
        CompilerResults results = csCompiler.CompileAssemblyFromSource(compilerParameters,
            new string[1] { temp });

        if (results.Errors.Count == 0){
            Assembly assembly = results.CompiledAssembly;
            MethodInfo calc = assembly.GetType("Eval").GetMethod("calc");
            double answer = (double)calc.Invoke(null, null);
            return answer;
        } else {
            Console.WriteLine("expression errors!");
            foreach(CompilerError err in results.Errors){
                Console.WriteLine(err.ErrorText);
            }
            return Double.NaN;
        }
    }
}
class Program {
    static void Main(){
        double value3 = 3;
        double value2 = 2;
        double value8 = 8;
        double value7 = 7;
        double value6 = 6;
        string calculate = " value3 / value2 * value8 / (36 * 840) * value7/ (2.2046 * value6) * value7";
        var vars = new Dictionary<string,string>();
        vars.Add("value3", value3.ToString("F"));
        vars.Add("value2", value2.ToString("F"));
        vars.Add("value8", value8.ToString("F"));
        vars.Add("value7", value7.ToString("F"));
        vars.Add("value6", value6.ToString("F"));
        double result = Sample.eval(calculate, vars);
        Console.WriteLine("{0:F8}", result);
    }
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

It is. The simplest way is simply calculate.Repalce("value1", value1.ToString()).Replace("value2", value2.ToString()) and then parse that while the most complex is a full-blown scripting language. StringBuilder could be used if you want to manipulate the same string multiple times.

::EDIT:: This question has been asked before. Take a look at the comments.

GGulati
  • 1,027
  • 6
  • 11
  • i'm having different type of opertors like value3 / value2 * value8 / (36 * 840) * value7/ (2.2046 * value6) by dynamically reading that string calculate... – Nagesh Hunter Jan 12 '12 at 08:13
0

There were several incorrect statements in your code.

The solution is:

int value1 =5 , value2 =10 ,value3;     
string calculate =value1.ToString() + value2.ToString(); // dynamic string
value3 = Convert.ToInt32(calculate );

This is because when you put value1 and value2 inside quotes they wont have any contents but become literals. Whereas you need their values. So convert them to strings and then do the third line or whatever else you want to do with them.

Mamta D
  • 6,310
  • 3
  • 27
  • 41
0

Perhaps you should do it with dictionary...something like this

Dictionary<string, int> d = new Dictionary<string, int>();
d["value1"] = 5;
d["value2"] = 10;
string calculate  = "value1 + value2";

string[] parts = string.Split(new[]{" + "}, StringSplitOptions.RemoveEmptyEntries);
int result = 0;
foreach(var part in parts)
{
  result += d[part];
}

// Do something with result
Aleksandar Vucetic
  • 14,715
  • 9
  • 53
  • 56
  • ya its too simple with simple calculations But my calculate expression is string calculate =" value3 / value2 * value8 / (36 * 840) * value7/ (2.2046 * value6) * value7" actually need to compute double result = convert.Todouble(calculate); – Nagesh Hunter Jan 12 '12 at 08:08