Using Reflection to Get the Value of a Nested Property

I recently ran into a situation wherein I needed to use reflection to get the value of a nested property. We were returning a custom type that inherits from JsonResponse, but this custom type is private to the controller class that uses it (I'm not sure why -- since we're returning it from some action methods I'd have thought it could be public. But I digress).

When writing some unit tests for these methods, I wanted to check the value of the success property which just so happens to be nested within the Data property. So I wrote a little method to assist with this, as shown below (the method and class names have been changed to protect the innocent).

The steps to follow are:
  1. Get the type of the object.
  2. Using the type, get the parent property of the nested property you want via Type.GetProperty(), specifying the name of the parent property as the parameter.
  3. Using the property, get its value using PropertyInfo.GetValue(), specifying the parent object and null as parameters.
  4. Get the type of the property from the parent property using the property object.GetType() chainged with GetProperty(). In the example below, I specified the name of the property I wanted, along with the type I'm expecting it to be.
  5. Get the value of the property you got in the previous step (the property you were looking for).
These steps are probably a little more difficult to follow than just reading the example code below, but they should help to make anything clear that the code itself may not express intuitively.

private static bool GetCustomJsonResultSuccessValue( 
   object customJsonResult)
    //Make sure the type we passed in is really the type we are expecting
    Type resultType = customJsonResult.GetType();
    if (!resultType.Name.Contains("CustomJsonResult"))
        throw new ApplicationException(
            "Passed object is not of type \"CustomJsonResult\", " + 
            "but rather \"{0}\"."
    //Get the Data property
    PropertyInfo dataProp = resultType.GetProperty("Data");
    if (dataProp == null)
        throw new ApplicationException("\"Data\" property not found.");
    //Get the value of the Data property
    Object data = dataProp.GetValue(customJsonResult, null);
    //Get the Data property's success property
    PropertyInfo successProp = data.GetType().GetProperty( 
    if (successProp == null)
        throw new ApplicationException("\"success\" property not found.");
    //Return the value of Data.success
    return (bool)successProp.GetValue(data, null);


Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

How To Mock Out Child Components In Unit Tests of Angular 2 Code