is short:
How can I invoke a base ctor after a child class ctor, without adding extra code in the child class ctor?
the entire story:
I have a base class ctor which loops through its child’s properties with reflection.
the only problem is that it must be called after thier initialization, which happens in the child class ctor.
public class Parent
{
public Parent()
{
DoReflectionStuff();
}
private void DoReflectionStuff()
{
// Do reflection stuff on child's properties
}
}
public class Child : Parent
{
public string Name { get; private set; }
public int Age { get; private set; }
public Child(string Name, int Age) : base()
{
this.Name = Name;
this.Age = Age;
}
}
I do not want to add extra code in the child ctor that calls DoReflectionSuff().
Please Help 🙂
Thank you
You can’t. The base ctor always has to run first.
You might want to look into the factory method pattern in order to control construction and configuration before getting an instance of the class. You must use the factory method to construct an instance of the class, and the factory method always ensures the instance is configured correctly before returning it.