9

Here is a DynamicDataObject class derived from DynamicObject

 public class DynamicDataObject : DynamicObject
 {
        private readonly Dictionary<string, object> _dataDictionary = new Dictionary<string, object>();

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

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (!_dataDictionary.ContainsKey(binder.Name))
            {
                _dataDictionary.Add(binder.Name, value);
                return true;
            }

            return false;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _dataDictionary.Keys;
        }
  }

and I am consuming DynamicDataObject like below.

 public MainWindow()
 {
     InitializeComponent();
     dynamic person = new DynamicDataObject();
     person.FirstName = "Vimal";
     person.LastName = "Adams";
     person.Address = null;
 }

I can see all members of person and it's values in the _dataDictionary but at the same time the debugger view excludes members having null value. So that person.Address member is not visible in the dynamic view collection.(please see the below screenshot). Can anyone please help me understanding why DynamicObjectbehaves differently in this scenario?

enter image description here

Vimal CK
  • 3,543
  • 1
  • 26
  • 47

1 Answers1

3

I think it is just an optimization. There is no use in keeping a reference to the default value of the type. It just returns default(T) when you try to access it.

It just behaves as a dictionary:

string property = "Address";
object val;

if (!dic.TryGetValue(property, out val))
{
    return default(T);
}
else
{
    return (T)val; // simplification
}

What is the point here to keep Address in the dictionary? None. That is why it is removed.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Some point developer has to set a property to null intentionally. That doesn't mean that it should not show in the list because of some optimization. Then the same behavor should work when we write LINQ also. Also it is showing member of value type if I am setting a int property with default value 0. So your assumption is wrong eg: person.Age = 0 – Vimal CK May 29 '15 at 14:14
  • I just thought the same so I test it. It seems it just checks for `null`. – Patrick Hofman May 29 '15 at 14:20