tags:

views:

1794

answers:

3

I am having trouble getting a nested objects properties. For the example I am working with, I have 2 Classes:

public class user 
{
  public int _user_id {get; set;}
  public string name {get; set;}
  public category {get; set;}
}

public class category 
{
  public int category_id {get; set;}
  public string name {get; set;}
}

Simple enough there, and if I reflect either one of them, I get the proper sets of GetProperties(), for example, if I do this:

PropertyInfo[] props = new user().GetType().GetProperties();

I will get the properties user_id, name and category, and if I do this:

PropertyInfo[] props = new category().GetType().GetProperties();

I will get the properties category_id and category; this works just fine. But, this is where I get confused...

As you can see, category is the last property of user, if I do this

//this gets me the Type 'category'
Type type = new user().GetType().GetProperties().Last().PropertyType;
//in the debugger, I get "type {Name='category', FullName='category'}"
//so I assume this is the proper type, but when I run this:
PropertyInfo[] props = type.GetType().GetProperties();
//I get a huge collection of 57 properties

Any idea where I am screwing up? Can this be done?

+2  A: 

By doing type.GetType() you are getting typeof(Type), not the property type.

Just do

PropertyInfo[] props = type.GetProperties();

to get the properties which you want.

However, you should look up properties by their name and not by their order, because the order is not guaranteed to be as you expect it (see documentation):

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

Lucero
I am not actually looking it up with .Last() - that was just for simplicity in the explanation.
naspinski
Very well. Since those questions are indexed by search engines, I'll leave my comment as-is because I feel that people should be aware that using the order must be avoided.
Lucero
wow, so simple... I was just thinking too hard (or maybe not enough), thanks!
naspinski
I agree about the .Last() comment, it was a very good point
naspinski
+1  A: 

Remove the GetType() from the type. Your are looking at the properties of the Type type itself.

Rune Grimstad
A: 

take a look for this

Tolgahan Albayrak
While this is a nice sample for reflection use, I don't think that it really helps the author of the question see what is going wrong in the code.
Lucero