4

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; 
}
nawfal
  • 70,104
  • 56
  • 326
  • 368

2 Answers2

3

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);
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
David
  • 19,389
  • 12
  • 63
  • 87
  • Thanks! I remove the above things. One problem I am encountering now is that there is a collection (array) of some class inside the original object. And the Activator.CreateInstance fails to create object of an array. –  Oct 08 '09 at 18:58
  • I found Array.CreateInstance but is takes size. The size is not known at this point! –  Oct 08 '09 at 19:17
  • Array.CreateInstance did not work out because it is already an array. –  Oct 08 '09 at 19:20
  • I've added to my answer, if it is dummy data, just make it a zero element array, or you could build those out as well – David Oct 08 '09 at 19:21
  • If the array is already initialized, then just skip it, or you could use reflection to get the length of the array. – David Oct 08 '09 at 19:39
1

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

Matt
  • 31,662
  • 4
  • 34
  • 33
  • I added it but it should return the original object that was passed filled with all the properties. Some properties are classes having their own properties. –  Oct 08 '09 at 18:54
  • Thanks! I remove the above things. One problem I am encountering now is that there is a collection (array) of some class inside the original object. And the Activator.CreateInstance fails to create object of an array. –  Oct 08 '09 at 19:07