This project has moved and is read-only. For the latest updates, please go here.

Run a known method

Nov 10, 2013 at 5:33 PM

I'd like to execute a know script method with parameters. Currently I use
because the Execute("MyMethod") hasn't got the option to call it with parameters. Am I wrong or is the use of the Script property the only way to execute a known method?

Nov 11, 2013 at 2:12 AM
Hello Torsten,

You can use Execute() or Evaluate() to invoke an existing script function, but doing so is suboptimal for several reasons.

First, as you've noted, these methods don't support argument passing. They execute arbitrary script code, and neither JavaScript nor VBScript provide standard conventions for argument passing in this context. You could of course invent your own conventions (e.g., storing arguments in a global script object with a well-known name), but that is a brittle approach that would only work for first-party script code.

The other factor to consider is that Execute() and Evaluate() are top-level entry points into the script engine's parsing and JIT compilation stack. They're relatively expensive. If all you need to do is invoke a script function that is already parsed and compiled, these methods are the wrong tool for the job.

The Script property gives you direct access to an existing script function, which you can then invoke without parsing or compiling additional script code. In addition to making it easy to pass arguments, this is important for performance. In fact, if the function is one that you call often, we recommend that you cache it and avoid going through Script every time:
dynamic myMethod = engine.Script.MyMethod;
// ...
object result = myMethod(parameter);
By the way, to access a global script function or object by name, you can do this:
dynamic myMethod = engine.Script["MyMethod"];
Good luck!