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; 
}
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);
}
You're missing a return obj; at the end of the if (obj != null) block...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With