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
Merging and fixing answers from Serj-TM and user3359453 so that it works with both ExpandoObject and DynamicJsonObject. This works for me.
public static bool HasPropertyExist(dynamic settings, string name)
{
if (settings is System.Dynamic.ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
if (settings is System.Web.Helpers.DynamicJsonObject)
try
{
return settings[name] != null;
}
catch (KeyNotFoundException)
{
return false;
}
return settings.GetType().GetProperty(name) != null;
}
This is working for me-:
public static bool IsPropertyExist(dynamic dynamicObj, string property)
{
try
{
var value=dynamicObj[property].Value;
return true;
}
catch (RuntimeBinderException)
{
return false;
}
}
This works for anonymous types, ExpandoObject, Nancy.DynamicDictionary or anything else that can be cast to IDictionary<string, object>.
public static bool PropertyExists(dynamic obj, string name) {
if (obj == null) return false;
if (obj is IDictionary<string, object> dict) {
return dict.ContainsKey(name);
}
return obj.GetType().GetProperty(name) != null;
}
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<string, object>)obj).ContainsKey(name))
return ((IDictionary<string, object>)obj)[name] != null;
return false;
}
if (obj is IDictionary<string, object> dict1)
{
if (dict1.ContainsKey(name))
return dict1[name] != null;
return false;
}
if (obj is IDictionary<string, JToken> 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;
}
Using reflection, this is the function i use :
public static bool doesPropertyExist(dynamic obj, string property)
{
return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}
then..
if (doesPropertyExist(myDynamicObject, "myProperty")){
// ...
}