Generic way to set property values with .NET
You can iterate over your object graph and set property values with reflection:
object obj; // your object
Type t = obj.GetType();
foreach (var propInfo in t.GetProperties())
{
propInfo.SetValue(obj, value, null);
}
If you can ensure that your class properties have getters you can iterate your object graph recursive:
public static void setValsRecursive(object obj, object value)
{
Type t = obj.GetType();
foreach (var propInfo in t.GetProperties())
{
if (propInfo.PropertyType.IsClass)
{
object propVal = propInfo.GetValue(obj, null);
setValsRecursive(propVal, value);
}
propInfo.SetValue(obj, value, null);
}
}
This is a dumb function that sets every property to the same value ...
You can use PropertyInfo
to dynamically set values in a generic way.