I have been struggling to get a simple DynamicObject example working in .NET 3.5.
Using the latest build of the DLR off codeplex I haven’t been able to figure out what the .NET 3.5 equivalent to the following is:
public class DynamicObjectBag : DynamicObject
{
private Dictionary<string, object> _properties = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _properties.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_properties[binder.Name] = value;
return true;
}
}
dynamic foo = new DynamicObjectBag();
foo.Val1 = 3;
foo.Val2 = “Value 2”;
This is of course a simplified example. I plan to derive classes from DynamicObject so I am able to use both direct object properties and properties stored in the dictionary using the same semantic dot style notation or access methods. The goal is to have DLR compatible objects for use in DLR supported languages and provide for future compatibility with .NET 4.0 DLR capabilities when the application can be upgraded to .NET 4.0.
My problem is that pre-.NET 4.0 I have no equivalent concept to the dynamic keyword. The methods such as TryGetMember have a binder parameter like GetMemberBinder. Now .NET 4.0 has a C# default binder available which will allow binding to happen when using the dynamic keyword, however I have been unable to find or determine how to perform the equivalent in .NET 3.5.
At the moment it is my understanding that I would need to write a custom binder which would basically duplicate the type of logic available in the .NET 4.0 default C# binder.
Please someone point me in the right direction on how I can use a DynamicObject in .NET 3.5 and add properties etc. at runtime without access to the dynamic keyword.
References:
http://stackoverflow.com/questions/2079870/dynamically-adding-members-to-a-dynamic-object
http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/