4

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).

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Dipak
  • 443
  • 6
  • 17

3 Answers3

4

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
  • 249,864
  • 45
  • 407
  • 398
  • Thanks Mark. But flee needs to be downloaded, hence I preferred JScript.Net. – Dipak Apr 15 '10 at 19:34
  • 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! – xyz Apr 28 '10 at 16:36
  • +1 to Flee - I evaluated over 50K expressions in 4 mins. Expressions were not complex, only arithmetic, and few null checks – Zasz Apr 17 '12 at 11:01
2

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.

Community
  • 1
  • 1
David M
  • 71,481
  • 13
  • 158
  • 186
1

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
  • 16,435
  • 14
  • 105
  • 149