Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change System.Dynamic.ExpandoObject default behavior


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?

like image 290
davidinho Avatar asked Dec 07 '25 02:12

davidinho


1 Answers

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
like image 125
pwas Avatar answered Dec 08 '25 14:12

pwas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!