Search code examples
c#clearscript

ScriptengineException when string methods are called


When I am using the following snippet, I get a ScrptEngineException, that the object does not support the Property or Method.

var engine = new JScriptEngine();
engine.AddHostType("String", typeof(System.String));
engine.ExecuteCommand("test = 'variabel'; test.StartsWith('nice');");

I have tried some other Stringfunctions like IndexOf, ToArray (Extension) and some others, but the do not seem to work.

Can someone help me out?


Solution

  • In your example, test is a JavaScript string, which has no StartsWith method. Even if it had been returned from .NET, it would have been converted to a JavaScript string for convenience.

    You can add a method that converts a JavaScript string to a .NET string:

    engine.AddHostObject("host", new HostFunctions());
    engine.Execute(@"
        String.prototype.toHost = function() {
            return host.newVar(this.valueOf());
        }
    ");
    

    And then this should work:

    engine.AddHostType(typeof(Console));
    engine.Execute(@"
        test = 'variable';
        Console.WriteLine(test.toHost().StartsWith('var'));
        Console.WriteLine(test.toHost().StartsWith('vaz'));
    ");
    

    BTW, be careful with this:

    engine.AddHostType("String", typeof(System.String));
    

    That hides the built-in JavaScript String function and is likely to break things.