Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 248
Omayr Avatar asked Nov 30 '25 14:11

Omayr


1 Answers

You can use the GetGenericArguments() method and do:

typeof(Order).GetProperty("OrderDetails").PropertyType.GetGenericArguments()[0]
like image 128
Frédéric Hamidi Avatar answered Dec 03 '25 03:12

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!