Rober
Rober

Reputation: 73

How get inner property value by reflection

I want to use the reflection to get the value from a class object. In this case, Rating is my main class which contains a property of Contribution class.

Following is the structure of my class

public class Rating
{
    public string personal_client_id { get; set; }
    public string risk_benefit_id { get; set; }
    public string type { get; set; }
    public string risk_event { get; set; }
    public string value { get; set; }

    public Contribution contribution { get; set; }

}

public class Contribution
{
    public string from { get; set; }
    public string value { get; set; }
}

Now I want the value from the contribution property like below.

var Rating = RatingObject.Where(x => x.personal_client_id == pcid).FirstOrDefault();
if (Rating  != null)
{
    Type type = Rating.GetType();
    PropertyInfo propertyInfo = type.GetProperty("contribution");
    var aa = propertyInfo.GetValue(Rating, null);

    //aa has the Contribution property now but i don't know how can i get the property value from 
   this object
   //Remember i dont want to do this **((Contribution)(aa)).from**

}
else
{
    return "";
}

Please help!

Upvotes: 0

Views: 243

Answers (2)

OwnBlood
OwnBlood

Reputation: 197

Instead of using var, you can force the type of aa to be a dynamic.

dynamic aa = propertyInfo.GetValue(Rating, null);
return aa.from;

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38618

Given you already have the rating object, you could define a PropertyInfo for the property you want to read from the Contribuition type and use the reference on the rating.contribution to read it. For sample

PropertyInfo propertyInfo = typeof(Rating).GetProperty("contribution");
var contribution = propertyInfo.GetValue(rating, null) as Contribution;

if (contribution != null)
{
   Console.WriteLine(contribution.from);
   Console.WriteLine(contribution.value);
}

Remember that PropertyInfo.GetValue method returns an something from object type, so, you have to cast it to the expected type.

Upvotes: 1

Related Questions