how to get the "class type" of a property in a class through reflection?

Omayr picture Omayr · Apr 16, 2011 · Viewed 9.1k times · Source

here is a piece of code

 public class Order
    {
        //Primary Key

    public long OrderId { get; set; }

    //Many to One Relationship
    [ParentObject("PersonId")]
    public Person Buyer { get; set; }

    //One to Many Relationship
    [ChildObject("OrderId")]
    public List<OrderDetail> OrderDetails { get; set; }

    public decimal TotalAmount
    {
        get
        {
            if (OrderDetails == null)
                return 0;

            return OrderDetails.Sum(o => o.LineItemCost);
        }
    }

    public string Notes { get; set; }
}

I am trying to examine the Order object. Now what I want to do is that: get all the properties and try to find out the class type for instance

public List<OrderDetail> OrderDetails { get; set; }

I want to get the type "OrderDetail" that is another class. When I try to get it using PropertyInfo.PropertyType I get "List1" (the Generic type), PropertyInfo.GetType() gives some System.Reflection.RuntimeType, PropertyInfo.DeclaringType gives "Order" (the class that contains the property). I would be obliged if anyone can propose a solution. Thanks in advance.

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · Apr 16, 2011

You can use the GetGenericArguments() method and do:

typeof(Order).GetProperty("OrderDetails").PropertyType.GetGenericArguments()[0]