Search code examples
clearscript

ClearScript: How to output an object?


Here is the C# code:

string jsScript = "var x = {A: 10, B: 100}";
scriptEngine.Evaluate(jsScript);
var result = scriptEngine.Evaluate("x");

The result is an instance of WindowsScriptItem object, how can I get the values 10 and 100?


Solution

  • If you know the object's property names, you can do this:

    dynamic dynamicResult = result;
    Console.WriteLine(dynamicResult.A);
    Console.WriteLine(dynamicResult.B);
    

    If you don't know the property names, you can do this:

    dynamic dynamicResult = result;
    foreach (var name in dynamicResult.GetDynamicMemberNames())
        Console.WriteLine("{0}: {1}", name, dynamicResult[name]);
    

    Obviously you'll need something more sophisticated if the object's property values can themselves be objects.