Question

I am getting "Object does not match target type" when I try to retrieve the value of a 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 Class BrokerInfo which has one property of type Broker which inturn has properties - FirstName and LastName (all strings for simplicity).

- BrokerInfo
  - Broker
    - FirstName
    - LastName

I am trying to recursively checking for custom types and trying to get their values. I am able to do for something like:

- Broker
  - FirstName
  - LastName

Please help.

Update: Was able to resolve it w/ the help of 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 to check if the type is custome type 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;
}
Was it helpful?

Solution

Why are you drilling down on the type, instead of the instance?

Specifically here:

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

It should look something like:

  var o = pinfo.GetValue(obj, null);
  GetMyProperties(o);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top