Reputation: 34687
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?
Upvotes: 4
Views: 8624
Reputation: 36300
Remove the GetType() from the type. Your are looking at the properties of the Type type itself.
Upvotes: 2
Reputation: 60190
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.
Upvotes: 4