I am trying to use reflection to achieve the following:
I need a method in which I pass an object, and this method will recursively create an object with child objects and set properties with default values. I need an entire instance of the object, going to as many levels as necessary.
this method should be able to process an object with several properties that will be shared lists of other objects.
Here is my sample code (I get a parameter counter mismatch exception when I get an object containing List<AnotherSetObjects>:
private void SetPropertyValues(object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (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);
}
}
}
thank
source
share