I have a method in which I like to perform a few different casts using reflection mechanism.
private static T GetObject<T>(Dictionary<string, object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
var p = type.GetProperty(kv.Key);
Type t = p.PropertyType;
Type t2 = kv.Value.GetType();
if (t == t2)
{
p.SetValue(obj, kv.Value);
}
else if (!IsPrimitive(p.PropertyType))
{
p.SetValue(obj, GetObject<class of p>((Dictionary<string, object>) kv.Value)); //???
}
else
{
p.SetValue(obj, (primitive)(kv.Value)); //???
}
}
return (T)obj;
}
EDITED
I have a dictionary and I want to convert it to a custom class, each key from dictionary is a property and each dictionary value is the value for that property. The problems appears in two cases, when both, the class property type and dictionary value type are primitives but they have different type (e.g. property is int but dictionary value is long), the second problem appears when property value is another custom class and in that case the dictionary value is always another dictionary
How can I detect dynamically the necessary cast/casts?