Hi All,
I am trying to to use reflection to achieve the following:
I need a method where i pass in an object and this method will recursively instantiate the object with child objects and set the properties with default values. I need the entire object instantiated going as many levels as needed.
this method needs to be able to handle an object with a multiple properties that will be generic lists of other objects.
Here is my sample code (I am getting a parameter count mismatch exception when i get an object containing a list:
private void SetPropertyValues(object obj)
{
System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo property in properties)
{
if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))
{
Type propType = property.PropertyType;
var subObject = Activator.CreateInstance(propType);
SetPropertyValues(subObject);
property.SetValue(obj, subObject, null);
}
else if (property.PropertyType == typeof(string))
{
property.SetValue(obj, property.Name, null);
}
else if (property.PropertyType == typeof(DateTime))
{
property.SetValue(obj, DateTime.Today, null);
}
else if (property.PropertyType == typeof(int))
{
property.SetValue(obj, 0, null);
}
else if (property.PropertyType == typeof(decimal))
{
property.SetValue(obj, 0, null);
}
}
}
Thanks