Filling out Object Properties with default values Recursive
c#, objectinstantiation, properties, reflection
Solution
You told it to `return null;`, try `return obj;` instead.
Also, remove the `return` from the `if (o != null) return InsertDummyValues(o);` line.
To answer your question in the comment...
else if (property.PropertyType.IsArray)
{
property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
Problem
I want to populate the object's properties with some dummy data. Here is my code but it always returns null. ``` private static object InsertDummyValues(object obj) { if (obj != null) { var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (var property in properties) { if (property.PropertyType == typeof (String)) { property.SetValue(obj, property.Name.ToString(), null); } else if (property.PropertyType == typeof(Boolean)) { property.SetValue(obj, true, null); } else if (property.PropertyType == typeof(Decimal)) { property.SetValue(obj, 23.5, null); } else { // create the object var o = Activator.CreateInstance(Type.GetType(property.PropertyType.Name)); property.SetValue(obj,o,null); if (o != null) return InsertDummyValues(o); } } } return obj; } ```