How do I check if a property exists on a dynamic anonymous type in c#?
public static bool DoesPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(DoesPropertyExist(settings, "Filename"));
Console.WriteLine(DoesPropertyExist(settings, "Size"));
Output:
True
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;
}
public static bool HasProperty(dynamic obj, string name)
{
Type objType = obj.GetType();
if (objType == typeof(ExpandoObject))
{
return ((IDictionary<string, object>)obj).ContainsKey(name);
}
return objType.GetProperty(name) != null;
}