This project has moved. For the latest updates, please go here.

Find an assumed method

Oct 20, 2013 at 1:20 PM
Hi ClearScript,

is there any option to find out if a script method exists or not except Try..Catch?

I do have the following scenario:
using (var engine = new V8ScriptEngine())
   engine.Execute(/* loaded script */ );

   var names = engine.Script.GetDynamicMemberNames() as IEnumerable<string>;

   // find out if MyMethod exists
   if (names != null && names.Contains("MyMethod"))
         engine.Script.MyMethod(/* parameters */);
It works but it is quite unsafe, because MyMethod might be everything but not the method I'm looking for with not the wanted parameters.

Best regards,
Oct 20, 2013 at 4:10 PM
Edited Oct 20, 2013 at 4:17 PM
Hello Torsten! Thanks for your question.

The best you can do in this case is determine whether a script object has a property with a given name, and if so, whether that property is a function with a given parameter count. Here's one way to do it:
dynamic hasMethod = engine.Evaluate(@"
    (function (obj, name, paramCount) {
        return (typeof obj[name] === 'function') && (obj[name].length === paramCount);
and then:
if (hasMethod(engine.Script, "MyMethod", 3))
   engine.Script.MyMethod(a, b, c);
Marked as answer by zimmybln on 10/20/2013 at 9:32 AM
Oct 20, 2013 at 4:30 PM
Works great!

Thanks a lot,