Search code examples
c#reflectionpropertyinfogetproperties

How can I access an object's property from the PropertyInfo?


When I foreach through an object's properties and end up with a PropertyInfo, how can I access the actual property of the object?

@foreach(var propertyInfo in Model.Entity.GetType().GetProperties()) {
    if (propertyInfo.PropertyType != typeof(string) &&
        propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null) {
        <div>
            @foreach(var item in propertyInfo/*Need Actual Property Here*/) {
                @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
            }
        </div>;
    }
}

Solution

  • Well, you need an instance to call it on - presumably that's Model.Entity in this case. You need the GetValue method. However, it's going to be quite tricky - because you need two things:

    • You need the value to be iterable by foreach
    • You need each item to have an Id property.

    If you're using C# 4 and .NET 4, you can use dynamic typing to make it a bit simpler:

    IEnumerable values = (IEnumerable) propertyInfo.GetValue(Model.Entity, null);
    @foreach(dynamic item in values) {
        @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
    }
    

    Or even:

    dynamic values = propertyInfo.GetValue(Model.Entity, null);
    @foreach(dynamic item in values) {
        @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
    }