1

I am inheriting from DynamicObject in my controller in nested class, and when I try to create property in ActionMethod it fails.

with SearchController.MyClass' does not contain a definition for 'Test' error, however class is declared in controller itself so I don't see how it can be not visible.

public class MyClass : DynamicObject
{
   public string Prop { get; set; }
}

public ActionResult Test()
{
   var test = ((dynamic)new MyClass()).Test = "sfdsdf"; // KABOOM here
 ....
}

How do set dynamic properties when inheriting from DynamicObject, why does this fail?

Community
  • 1
  • 1
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265

1 Answers1

4

Seems like you are expecting the behavior provided by the ExpandoObject. However, the DynamicObject is just

a base class for specifying dynamic behavior at run time.

The class itself does not provide any functionality, but helps you implement that by overriding only the methods that you need, as described in the Remarks section of the documentation:

To implement the dynamic behavior, you may want to inherit from the DynamicObject class and override necessary methods. For example, if you need only operations for setting and getting properties, you can override just the TrySetMember and TryGetMember methods.

So, in order to support dynamically adding properties at runtime, you should declare some storage and handle the aforementioned methods (note that they will not be called for the real properties of your class) like this:

public class MyClass : DynamicObject
{
    public string Prop { get; set; }

    Dictionary<string, object> dynamicMembers = new Dictionary<string, object>();

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

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return dynamicMembers.TryGetValue(binder.Name, out result);
    }
}

Now this will work:

var c = (dynamic)new MyClass();
c.Test = "sfdsdf"; // No KABOOM here :)
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • 1
    Hi Ivan, in my defense i can say that it is quite surprising that there is no default implementation in .NET. for `DynamicObject`. I am so happy that our work time-zones overlap :) – Matas Vaitkevicius Jun 23 '16 at 08:37