How to get the list of properties of a class?

Sukesh picture Sukesh · Apr 10, 2009 · Viewed 538.6k times · Source

How do I get a list of all the properties of a class?

Answer

Marc Gravell picture Marc Gravell · Apr 10, 2009

Reflection; for an instance:

obj.GetType().GetProperties();

for a type:

typeof(Foo).GetProperties();

for example:

class Foo {
    public int A {get;set;}
    public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}

Following feedback...

  • To get the value of static properties, pass null as the first argument to GetValue
  • To look at non-public properties, use (for example) GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) (which returns all public/private instance properties ).