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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With