I have an anonymous type object that I receive as a dynamic from a method I would like to check in a property exists on that object.
....
var settings = new
To extend the answer from @Kuroro, if you need to test if the property is empty, below should work.
public static bool PropertyExistsAndIsNotNull(dynamic obj, string name)
{
if (obj == null) return false;
if (obj is ExpandoObject)
{
if (((IDictionary)obj).ContainsKey(name))
return ((IDictionary)obj)[name] != null;
return false;
}
if (obj is IDictionary dict1)
{
if (dict1.ContainsKey(name))
return dict1[name] != null;
return false;
}
if (obj is IDictionary dict2)
{
if (dict2.ContainsKey(name))
return (dict2[name].Type != JTokenType.Null && dict2[name].Type != JTokenType.Undefined);
return false;
}
if (obj.GetType().GetProperty(name) != null)
return obj.GetType().GetProperty(name).GetValue(obj) != null;
return false;
}