Adding properties or Dynamic objects in ClearScript

Feb 14, 2013 at 11:42 AM

could you please clarify how ClearScript works with dynamic objects?

I have tried following code:
dynamic testObj = new ExpandoObject();
testObj.str = "testString";
When I evaluate "testObj.str" I see "[undefined]" , however in .net environment I am able to see
the str value.

Also I have found IDynamic interface, but it is internal and I am not able to use it in my code.

The main reason I am asking about this is that I see an exception on defining property, that doesn't exist, from the js code.

For example (.net side):
engine.AddHostObject("myObj", new Object());
Js Code:
myObj.foobar = "newString";
At this point i will have an exception of type 'System.MissingMemberException'
occurred in ClearScript.dll. "Object has no property or field named 'foobar'"

So that is why I concerned about dynamic. BBut maybe there is some other good way to have necessary functionality.
Feb 14, 2013 at 2:34 PM
Edited Aug 3, 2013 at 2:36 AM
Hi pro100sanya,

Thank you for this excellent question!

First, let's clarify our terminology. When you say "dynamic objects", you seem to be talking about host objects that provide custom behavior in conjunction with the dynamic keyword. For example, ExpandoObject, when accessed via dynamic, makes it look like the objects stored in its internal dictionary are properties of the ExpandoObject instance itself.

ClearScript currently does not provide convenient access to this functionality from script code. If you expose an ExpandoObject instance, script code can manipulate its dynamic properties via IDictionary<string, object>, but not directly as in C# with dynamic. This is a great idea for a new feature!

You do have a couple of options available today. Instead of ExpandoObject, consider using ClearScript's PropertyBag class, or any class that implements ClearScript's IPropertyBag interface. This interface has special meaning in ClearScript that provides the script-side convenience you're looking for, but not the dynamic support on the host side:
var testObj = new PropertyBag();
engine.AddHostObject("testObj", testObj);
testObj["str"] = "testString";
var testString = engine.Evaluate("testObj.str");
Another option might be to use a script object:
dynamic testObj = engine.Evaluate("testObj = {}");
testObj.str = "testString";
var testString = engine.Evaluate("testObj.str");
Does either alternative satisfy your requirements? We'd love to hear more about your particular scenario!
Feb 19, 2013 at 12:59 AM
We are now tracking the dynamic host object projection issue here.