0
Class foo
{
   public string name;
   public int age;
   public datetime BirthDate;
}

I have the above class.

I want the list of variables of the foo class.

I tried

foo fooObj= new foo();
fooObj.GetType().GetProperties()

This returned me 0 properties.

Obviously this wont work as there are no properties in class foo.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
MARKAND Bhatt
  • 2,428
  • 10
  • 47
  • 80
  • 1
    These are fields, not properties – GôTô Apr 28 '14 at 12:54
  • In most cases reflection is the wrong tool, why do you need to get the proeprties/fields in this way at all? – Tim Schmelter Apr 28 '14 at 12:54
  • 1
    You got `Fields` there not `Properties`. – Hassan Apr 28 '14 at 12:55
  • @Tim Schmelter. if reflection is the wrong tool then whats the best way to access properties/fields? – MARKAND Bhatt Apr 28 '14 at 12:58
  • 1
    As a random aside: why aren't those properties? `public string Name {get;set;}` would be preferable in **every**. **single**. **way**. And actually, `age` and `BirthDate` are redundant anyway... (one implies the other) – Marc Gravell Apr 28 '14 at 13:04
  • 1
    @MARKANDBhatt: `string fooName = foo.Name;` (you should also follow .NET [naming conventions](http://msdn.microsoft.com/en-us/library/ms229043(v=vs.110).aspx)) – Tim Schmelter Apr 28 '14 at 13:05

2 Answers2

10

Your class has fields, not properties. A property has getter and setter methods, while a field just stores data.

Try

typeof(foo).GetFields()

or change your fields to properties:

Class foo
{
   public string name {get; set;}
   public int age {get; set;}
   public datetime BirthDate {get; set;}
}

Or, to get fields and properties, use:

typeof(foo).GetMembers()
           .Where(mi => mi.MemberType == MemberTypes.Field || 
                        mi.MemberType == MemberTypes.Property);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
4

Have you tried this:

new foo().GetType().GetFields()

Those are fields and not properties and GetType is a method of object.

Just doing foo.GetType() will throw an error.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95