views:

295

answers:

1

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/

+1  A: 

You will need to create a custom binder and you will probably then want to consume the binder using a CallSite so that the actions are cached.

You can use the DefaultBinder in the outer layer to do most of this - you just need to create one and then it has methods like GetMember on it to do the binding. The implementation of your binder then is just using the DefaultBinder and applying any rules for boxing value types that come back (the DLR requires all return types to be object).

Dino Viehland
That is my current thought was well. I am hoping there is some secret ninja move that I am missing so I don't have to write a custom binder and callsite given this type of behavior is available in .NET 4.0.
Firestrand