C# .NET - ...How to do ? - Asked By shah zeb on 21-Nov-11 12:36 AM

if a string contains
str testStr = "10+90/4*34 -2";
and i need its mathematical output what should be done?
Riley K replied to shah zeb on 21-Nov-11 12:44 AM

If you want to validate a string containing "2+1-(3*2)+8/2" in C#, you're either going to have to write a math expression parser/evaluator, or use the CodeDom support to compile the code to C# (with its syntax restrictions) and call the code directly.

Apart from a couple of expression evaluators:

You could also create a DataTable, add a DataColumn and exploit it's Expression property Wink

string expression = "2+1-(3*2)+8/2";
DataTable dataTable = new DataTable();
dataTable.Columns.Add("col1", typeof(int), expression);
dataTable.Rows.Add(new object[] { });

Reena Jain replied to shah zeb on 21-Nov-11 01:49 AM

First you call the static Initialise, the pass your string to EvaluateStringAsDouble() and it gives you the result back as a double.

check this

using System;
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
namespace VPDBUtils
public class JScriptEvaluator
private static VsaEngine vsaEngine;
public static void Initialize()
vsaEngine = VsaEngine.CreateEngine();
public static void Close()
if (vsaEngine != null)
private static object EvaluateString(string sStringToEvaluate)
return Eval.JScriptEvaluate(sStringToEvaluate, vsaEngine);
internal static double EvaluateStringAsDouble(string sStringToEvaluate)
return System.Convert.ToDouble(EvaluateString(sStringToEv aluate));

here is the link for more help
Suchit shah replied to shah zeb on 21-Nov-11 04:53 AM
The Matematical Output of this you get by using following steps :
1. Define Your String
String testStr = "10+90/4*34 -2";
2. Pass your string in this Expression ( This is the main line which perform operation)

object value = new DataTable().Compute(testStr, null);

3. Display the result in Label

lbl1.Text = Convert.ToString(value);

Output : 773

It is actually possible with the .NET framework:

object value = new DataTable().Compute(teststr, null);

This is the Line which peform the Mathematical operation

Check it out and let me know

shah zeb replied to Suchit shah on 21-Nov-11 06:17 AM
Great !!
It i working
Thank U
Suchit shah replied to shah zeb on 21-Nov-11 06:40 AM