3


I've a dynamic object created using System.Dynamic.ExpandoObject(), now in some cases some properties could not exists, and if try to access to those in this way

myObject.undefinedProperties;

the default behavior of the object is to throw the exception

'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'

Is possible to change this behavior and return in that case the null value?

davidinho
  • 169
  • 1
  • 14

3 Answers3

4

If you could replace ExpandoObject with DynamicObject, you could write own class that meets your requirements:

public class MyExpandoReplacement : DynamicObject
{
    private Dictionary<string, object> _properties = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (!_properties.ContainsKey(binder.Name))
        {
            result = GetDefault(binder.ReturnType);
            return true;
        }

        return _properties.TryGetValue(binder.Name, out result);
    }

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

    private static object GetDefault(Type type)
    {
        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        return null;
    }
}

Usage:

dynamic a = new MyExpandoReplacement();
a.Sample = "a";

string samp = a.Sample; // "a"
string samp2 = a.Sample2; // null
pwas
  • 3,225
  • 18
  • 40
  • The type passed into GetDefault(Type type) seems to always be 'object' and never goes down the type.IsValueType branch. Why? – WillC Jun 28 '17 at 22:46
2

ExpandoObject inherits IDictionary <string, object> so you can check if the object has "undefinedProperties" like this

if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties"))
{
    // Do something
}
jhmt
  • 1,401
  • 1
  • 11
  • 15
1

You can test the existence of property in the ExpandoObject, see here Detect property in ExpandoObject

Community
  • 1
  • 1
aguetat
  • 514
  • 4
  • 18