I have POCO object MyObject
public class MyModel
{
public MyProperty MyProperty001 { get; set; }
public MyProperty MyProperty002 { get; set; }
MyModel()
{
// New up all the public properties
var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var propertyInfo in properties)
{
//Activator.CreateInstance()
}
}
}
that has hundreds of properties, is it possible using reflection to instantiate these in the constructor? I have the PropertyInfo, but don’t know what is the next step.
Thank you,
Stephen
Type of property holds within of
PropertyTypeproperty ofPropertyInfoobject, so according to that you can instantiate your objects by callingActivator.CreateInstance(propertyInfo.PropertyType). Than you need to set instance into property of your container object by callingpropertyInfo.SetValue(this, instance, null)Full sample: