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

Leave a Comment