One of the previous posts in my general programming blog talks about evaluating the arithmetic expressions using the DataColumn and DataTables.The requirement was simple.You are given with an arithmetic expression say “(2+2)*3” as string. May be a user entered expression.You need to evaluate the given expression and show the answer.
In .Net it is easier.Use a DataColumn with the given expression and it will calculate the result for you.But when we come to Silverlight the things get harder.There is no concept of DataSet or DataTable in Silverlight.Rather the ADO.Net is not there.So what can we do?
One solution is to have a WCF server call which accepts the expression as string and use the ADO.Net DataColumn at server-side and return back the result.Obviously you can achieve that since the server is just a .Net application with ADO.Net support.But is that the better solution? I will say No because we have another alternative.
Its nothing but the famous eval function of javascript.I think all of you know how Silverlight can communicate with Javascript.If not please read this post about the same.
Here goes the solution.Get your expression.Pass it to the eval method of HtmlWindow.Use the return value properly.
private double Evaluate(string expression)
{
object obj = HtmlPage.Window.Eval(expression);
return Convert.ToDouble(obj);
}