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 :)