Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling out Object Properties with default values Recursive

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; 
}

2 Answers

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);
}
like image 71
David Avatar answered Sep 14 '25 17:09

David


You're missing a return obj; at the end of the if (obj != null) block...

like image 44
Matt Avatar answered Sep 14 '25 16:09

Matt