views:

163

answers:

3

I am trying to parse formula in C# language like

"5*3 + 2" 
"(3*4 - 2)/5"

Is it possible to do in C# or scripts like VBScript, JavaScript (which will be called in c# program).

+2  A: 

I've had great experience with Flee, a C# library that evaluates expressions such as the one you've described. You can evaluate the expressions as strongly typed statements, so if you wanted an integer for example, "(1 + 2) * 5" would be okay but "hello world" would not.

You can even hook in specific variables or functions. The Flee examples page is a great starting point.

Mark Rushakoff
Thanks Mark. But flee needs to be downloaded, hence I preferred JScript.Net.
Cool
It's in fact a VB.NET library. I got freaked out when I took a look at the source to try to understand some issues I was having!
frou
+2  A: 

There's a trick I've used before to do this sort of thing in C#, which is to use JScript.NET's eval function. You'll find the complete code in my answer to this question. It's not relying on a scripting language like VBScript or JavaScript, it's pure .NET, and the implementation I use generates a JScript.NET assembly on the fly from C# code, so there's no need to mix languages in your solution.

David M
Thanks David, this is what I want.
Cool
+1  A: 

I've successfully used the Dynamic Linq sample from Microsoft to dynamically formulate expressions which use types under the System.Linq.Expressions namespace. This works very well for me and allows me to use a more natural C# syntax in place of ActiveReports default expressions.

jpierson