Search code examples
c#reflectionsubobject

How to access subObject properties values in c#


I am trying to loop over an object properties and values and build a string with them. The problem is i cant seem to access the values of the properties which are not string...

Here is what i have so far:

    private string ObjectToStringArray(CustomType initParameters)
    {
        var stringArray = "";

        foreach (var parameter in initParameters.GetType().GetProperties())
        {
            if (parameter.PropertyType.Name == "String")
                stringArray += "\"" + parameter.Name + "\" => \"" + parameter.GetValue(initParameters) + "\",\r\n";
            else
            {
                stringArray += "array(\r\n";
                foreach (var subParameter in parameter.PropertyType.GetProperties())
                {
                    stringArray += "\"" + subParameter.Name + "\" => \"" + subParameter.GetValue(parameter) + "\",\r\n";
                }
                stringArray += "),";
            }
        }

        return stringArray;
    }

i can get to the values of all the string properties but one level down i just cant extract the property object itself.

My exception is: System.Reflection.TargetException: Object does not match target type.


Solution

  • When calling subParameter.GetValue(parameter), you are passing a PropertyInfo, whereas you seemingly want to pass the value of that property for initParameters instead.

    You should thus pass parameter.GetValue(initParameters) to subParameter.GetValue() instead.