4

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am not actually looking it up with .Last() - that was just for simplicity in the explanation.
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.
wow, so simple... I was just thinking too hard (or maybe not enough), thanks!
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.