Sunday, December 27, 2009

Evaluating arithmetic expressions using DataColumn

When somebody wants to get calculated result for an input string such as “(2+2)*2+2” what you will do? The normal developers will think about writing a parser ,expression evaluator etc…because they think that, this is not possible using existing APIs and they also take this as an opportunity to write their own parser.
Even I was also thinking about the same until I found the support in .Net DataColumn.There is one overload in the DataColumn constructor which accepts the expression and fills the value in all the datarows when they are being added into DataTable.

private double Evaluate(string expression)
{
DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn("Result", typeof(double), expression));

DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
return Convert.ToDouble(dt.Rows[0]["Result"]);
}


You may catch the exception if the syntax is wrong in the given expression.



private void btnEvaluate_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show(Evaluate(tbExpression.Text).ToString());
}
catch (SyntaxErrorException synEx)
{
MessageBox.Show(synEx.Message);
}
}


See the application in action below