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
I'm not sure why these answer are so complex, try:
dynamic settings = new
{
Filename = "temp.txt",
Size = 10
};
string fileName = settings.Filename;
var fileNameExists = fileName != null;
None of the solutions above worked for dynamic
that comes from Json
, I however managed to transform one with Try catch
(by @user3359453) by changing exception type thrown (KeyNotFoundException
instead of RuntimeBinderException
) into something that actually works...
public static bool HasProperty(dynamic obj, string name)
{
try
{
var value = obj[name];
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
Hope this saves you some time.
public static bool IsPropertyExist(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(IsPropertyExist(settings, "Filename"));
Console.WriteLine(IsPropertyExist(settings, "Size"));
Output:
True
False
In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.
public static bool PropertyExists(dynamic obj, string name)
{
if (obj == null) return false;
if (obj is ExpandoObject)
return ((IDictionary<string, object>)obj).ContainsKey(name);
if (obj is IDictionary<string, object> dict1)
return dict1.ContainsKey(name);
if (obj is IDictionary<string, JToken> dict2)
return dict2.ContainsKey(name);
return obj.GetType().GetProperty(name) != null;
}
if you can control creating/passing the settings object, i'd recommend using an ExpandoObject instead.
dynamic settings = new ExpandoObject();
settings.Filename = "asdf.txt";
settings.Size = 10;
...
function void Settings(dynamic settings)
{
if ( ((IDictionary<string, object>)settings).ContainsKey("Filename") )
.... do something ....
}
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;
}