Evaluating an expression

The following code will evaluate a javascript expression:

var engine = new Jurassic.ScriptEngine();
Console.WriteLine(engine.Evaluate("5 * 10 + 2"));
This code will output "52" to the console.

You can include multiple statements in the code string; the result of the last valid expression will be returned.

The above call to Evaluate returns an object. If you want to return a value of a specific type, you can use the coercing version of Evaluate. For example:

var engine = new Jurassic.ScriptEngine();
Console.WriteLine(engine.Evaluate<int>("1.5 + 2.4"));
This code outputs "3" to the console. (If you are wondering why it returns 3, rather than 4, the conversion to an integer uses the javascript type conversion rules, which specify that numbers are rounded towards zero). Type coercian is only supported for certain types.

Next tutorial: Executing a script

Last edited Aug 25, 2010 at 2:50 PM by paulbartrum, version 9


No comments yet.