Rob
Rob

Reputation: 638

How to compute expression

Consider this code fragment;

int sum = 0;
sum = Expression.Evaluate("1+1");

where the value of sum = 2

I do have an expression that will compute values but i want that expression to be build programatically then evaluate the result. I don't have any idea what class or namespace that I will dealing with. Anyone can help me.

Upvotes: 1

Views: 1869

Answers (3)

GreyCloud
GreyCloud

Reputation: 3100

Have you seen http://ncalc.codeplex.com ?

It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");

  e.Parameters["Pi2"] = new Expression("Pi * Pi");
  e.Parameters["X"] = 10;

  e.EvaluateParameter += delegate(string name, ParameterArgs args)
    {
      if (name == "Pi")
      args.Result = 3.14;
    };

  Debug.Assert(117.07 == e.Evaluate());

It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

It also supports logical operators, date/time's strings and if statements.

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300559

You could use Expression Trees:

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

You can compile and run code represented by expression trees.

Note: This problem can be solved using System.Reflection.Emit and work directly with MSIL, but the resulting code is hard to write and read.

After a little browsing, I suggest you checkout Flee on Codeplex: Fast Lightweight Expression Evaluator :

Flee is an expression parser and evaluator for the .NET framework. It allows you to compute the value of string expressions such as sqrt(a^2 + b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions directly to IL. This means that expression evaluation is extremely fast and efficient.

Upvotes: 1

m0sa
m0sa

Reputation: 10940

You can build Expressions trees either using lambdas or by building them programatically using classes in the System.Linq.Expressions namespace.

See MSDN for more info.

Upvotes: 0

Related Questions