0

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.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
RealGigex
  • 346
  • 2
  • 18

1 Answers1

1

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.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
  • This is the problem, how do i access that value? Using `initParameters` returns the same excpetion. – RealGigex Mar 18 '15 at 13:48
  • @RealGigex Just like you output the value of the string by calling `parameter.GetValue(initParameters)`, so should you get the actual value of the property, rather than its `PropertyInfo` by calling `parameter.GetValue(initParameters)`. That call means, _"for this type of property, get the value for the specified instance that contains that property"_. In other words, `subParameter.GetValue(parameter.GetValue(initParameters))`, not just `subParameter.GetValue(initParameters)`. Just trying to make you understand what is going on. ;p P.s. you could probably use recursion to implement this. – Steven Jeuris Mar 18 '15 at 13:51
  • Thank you! that did the trick! I was also missing some null validations on the sub objects. – RealGigex Mar 18 '15 at 13:54