Matthew Scharley
Matthew Scharley

Reputation: 132234

Subclassing DynamicObject in C# 4.0?

I've been testing out some of the new stuff in VS 2010 and C# 4.0, and been pushing at things a little to see the limits of it, and so far I like what I see, but one thing has me slightly annoyed...

Given the following two simple classes, is there some way (other than calling TryGetMember directly) to avoid the cast to dynamic? Perhaps some magic attribute that can be set on Test?

class DynamicPropertyObject : DynamicObject
{
    private Dictionary<string, object> _properties = new Dictionary<string, object>();

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        foreach (string s in _properties.Keys)
            yield return s;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _properties[binder.Name] = value;
        return true;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;
        if (!_properties.ContainsKey(binder.Name))
            return false;

        result = _properties[binder.Name];
        return true;
    }
}

class Test : DynamicPropertyObject
{
    public Test()
    {
        ((dynamic)this).Foo = "test";
    }
}

Upvotes: 0

Views: 1063

Answers (2)

Pavel Minaev
Pavel Minaev

Reputation: 101555

There's no magic attribute to force a class always be treated as if it was dynamic. However, if your problem is specifically that you want it for this inside the class, just add a helper property:

private dynamic DynThis { get { return this; } }

and use it instead.

Upvotes: 1

Cecil Has a Name
Cecil Has a Name

Reputation: 4992

I suspect you need the cast to dynamic so that the compiler can convert the property access into a TryGetMember class.

Edit:

Since .NET and C# are not exactly dynamic nor intended to always be late bound (except for virtual members), it is necessary to explicitly state that you want dynamic typing when you do. There is no in-between: a statically typed object var which acts as dynamically typed when the compiler cannot find the member at compile-time.

Upvotes: 2

Related Questions