Search code examples
c#javascriptjint

Specified Cast Is not valid in Jint 2.0


I'm just starting to use Jint 2.0 in my c# application. However I cannot seem to be able to retrieve a value from within Jint.

Even with the example code provided:

            var engine = new Jint.Engine();
            engine.Execute(@" function add(x, y) {   return x + y;  } var z = add(3, 2);");

            var z = engine.GetValue("z");
            Console.WriteLine(z); // -> 5

The line var z = engine.GetValue("z"); is throwing an InvalidCastException (specified cast is not valid)

Considering this is the example code, is there something simple I'm missing?

UPDATE: I was able to get it to work if I changed 'GetValue' to GetGlobalValue'. I would still like to know why this is, so I'm leaving the question open.


Solution

  • Please upgrade to version 2.1.0.0. I have tried your code with this latest version and it does not throw InvalidCastException. The latest version has had several changes and bugfixes. A simple explanation would be that in 2.0 the GetGlobalValue function first retrieves the value object itself from the Global scope and then passes it to the GetValue function. In version 2.1 this is combined and therefore you will not get the InvalidCastException thrown.

    Also good to know is that the engine.GetValue function always returns a JsValue object. You can add the AsNumber() function which returns the value as a Double.

            var engine = new Jint.Engine();
            engine.Execute(@" function add(x, y) {   return x + y;  } var z = add(3, 2);");
    
            var z = engine.GetValue("z").AsNumber();
            Console.WriteLine(z); // -> 5
    

    As there is little documentation I recommend to look at the tests written for Jint at https://github.com/sebastienros/jint/tree/master/Jint.Tests/Runtime.