David MZ David MZ - 1 year ago 265
C# Question

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 {

function void Settings(dynamic settings) {
var exists = IsSettingExist(settings,"Filename")

How would I implement IsSettingExist ?

Answer Source
  public static bool IsPropertyExist(dynamic settings, string 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"));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download