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

Cast Script result

Nov 1, 2013 at 5:08 PM
What's the most straight forward way to cast the result of a dynamic Script call?

var foo = engine.Script.getFoo(bar);

I was looking for something like foo.ToJson() and then use to deserialize into Foo.

Maybe serialize foo with and then back to Foo? Or is there something built in that I've missed in the docs?
Nov 1, 2013 at 5:20 PM
Hi! Thanks for your question.

What kind of object or value are you expecting getFoo() to return? That is, how does that function construct or acquire its return value?

Also, what is Foo?
Nov 1, 2013 at 5:26 PM
Something like

class Foo {
public string Name {get; set; }

var engine = new V8ScriptEngine();
engine.Execute("function getFoo(bar) { return { 'Name': bar.Something } }");
var foo = engine.Script.getFoo(bar);

//TODO: cast the variable foo to type Foo.
Nov 1, 2013 at 5:50 PM
Edited Nov 2, 2013 at 12:54 AM
Your script function is returning a script object. There are several ways to convert it to a .NET object.

One way would be via simple property assignment:
dynamic foo = engine.Script.getFoo(bar);
var clrFoo = new Foo { Name = foo.Name };
JSON is certainly another possibility:
var foo = engine.Script.getFoo(bar);
var jsonFoo = (string)engine.Script.JSON.stringify(foo);
var clrFoo = JsonConvert.DeserializeObject<Foo>(jsonFoo);  // Json.NET call
Another approach might be to return a .NET object from the script function:
engine.AddHostType("Foo", typeof(Foo));
engine.Execute(@"function getFoo(name) {
    var foo = new Foo();
    foo.Name = name;
    return foo;

var clrFoo = (Foo)engine.Script.getFoo("Paul");
Please let us know if none of these are practical in your scenario!
Nov 1, 2013 at 5:52 PM
They are all practical. Option 2 is what I was looking for. Thanks!