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:
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:
- Get the type of the object.
- 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.
- Using the property, get its value using PropertyInfo.GetValue(), specifying the parent object and null as parameters.
- 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.
- Get the value of the property you got in the previous step (the property you were looking for).
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(
String.Format(
"Passed object is not of type \"CustomJsonResult\", " +
"but rather \"{0}\".",
resultType.Name)); //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(
"success", typeof(bool)); if (successProp == null) throw new ApplicationException("\"success\" property not found."); //Return the value of Data.success return (bool)successProp.GetValue(data, null); }
Comments
Post a Comment