Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new dynamic properties

Tags:

c#-4.0

we read in msdn we "Adding new dynamic properties" by using DynamicObject Class i write a following program

public class DemoDynamicObject : DynamicObject
{

}
class Program
{
    public static void Main()
    {
        dynamic dd = new DemoDynamicObject();
        dd.FirstName = "abc";
    }
}

But when i run this program it gives runtime error :'DemoDynamicObject' does not contain a definition for 'FirstName' if we adding dynamic property by using DynamicObject Class then why it can give this error can anyone tell me reason and solution?

like image 701
Vikram Avatar asked Dec 15 '10 14:12

Vikram


1 Answers

When using DynamicObject as your base class, you should provide specific overrides to TryGetMember and TrySetMember to keep track of the dynamic properties you are creating (based on the DynamicObject MSDN documentation):

class DemoDynamicObject: DynamicObject
{
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }

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

If you just want to have a dynamic object that you can add properties to, you can simply use an ExpandoObject instance, and skip the custom class inheriting from DynamicObject.

like image 63
JeremyDWill Avatar answered Jan 01 '23 02:01

JeremyDWill