How do I check if a property exists on a dynamic anonymous type in c#?
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 {
Filename="temp.txt",
Size=10
}
...
function void Settings(dynamic settings) {
var exists = IsSettingExist(settings,"Filename")
}
How would I implement IsSettingExist ?
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
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;
}
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 ....
}