PropertyInfo GetValue error during recursion

I get "Object does not match the target type" when I try to get the value of an object at runtime in my C # program.

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); //throws error during recursion call
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.PropertyType;
      GetMyProperties(o);
    }
  }
}

I pass an object of my BrokerInfo class, which has one property of type Broker, for which inturn has properties - FirstName and LastName (all lines for simplicity).

- BrokerInfo
  - Broker
    - FirstName
    - LastName

I am trying to recursively check user types and try to get their values. I can do something like:

- Broker
  - FirstName
  - LastName

Please, help.

Update: managed to resolve it with leppie: here is the modified code.

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); 
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.GetValue(obj, null);
      GetMyProperties(o);
    }
  }
}

IsCustom is my method of checking type type custome or not. Here is the code:

public static bool IsCustomType(Type type)
{
    //Check for premitive, enum and string
    if (!type.IsPrimitive && !type.IsEnum && type != typeof(string))
    {
        return true;
    }
    return false;
}
+3
source share
1 answer

Why are you drilling a type, not an instance?

In particular here:

  object o = pinfo.PropertyType;
  GetMyProperties(o);

It should look something like this:

  var o = pinfo.GetValue(obj, null);
  GetMyProperties(o);
+5

Source: https://habr.com/ru/post/1789349/


All Articles