Use reflection for that.
public class ChildAttribute : Attribute
{ }
public class Parent
{
public string AnotherProperty { get; set; }
[Child]
public ChildClass Child { get; set; }
}
public class ChildClass
{
public string Name { get; set; }
}
static void Main(string[] args)
{
var parent = new Parent();
foreach (PropertyInfo propertyInfo in parent.GetType().GetProperties())
{
var childAttribute = propertyInfo.GetCustomAttribute<ChildAttribute>();
if (childAttribute != null)
{
//Get value of child property
var childPropertyValue = propertyInfo.GetValue(parent);
propertyInfo.SetValue(parent, new ChildClass { Name = "Child class created from reflection" });
}
}
bool result = parent.Child.Name == "Child class created from reflection";
}