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);
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)
{
if (!type.IsPrimitive && !type.IsEnum && type != typeof(string))
{
return true;
}
return false;
}
source
share