Is there a way to do this in C#? I know that the subclass will call the superclass constructor before calling its own constructor, but what If I have some code on the superclass that should only be executed after all the subclasses constructors have been called?
views:
111answers:
5class A : B
{
public A() : base()
{
base.doSomething();
}
}
class B : C
{
public B() : base()
{
}
public void doSomething() { /* ... */ }
}
class C
{
public C() { /* ... */ }
}
Execution Order should be:
- C::ctor()
- B::ctor()
- A::ctor()
- B::doSomething()
I'm not sure what you mean - can't you just call the code in the super class at the end of our last subclass constructor? Alternatively you could call it directly after instantiation.
class Program
{
static void Main(string[] args)
{
SubSub obj = new SubSub();
//obj.DoStuff();
Console.ReadLine();
}
}
class Super
{
public Super()
{
Console.WriteLine("Constructing Super");
}
public void DoStuff()
{
Console.WriteLine("Doin' stuff");
}
}
class Sub : Super
{
public Sub()
{
Console.WriteLine("Constructing Sub");
}
}
class SubSub : Sub
{
public SubSub()
{
Console.WriteLine("Constructing SubSub");
DoStuff();
}
}
This will output:
Constructing Super
Constructing Sub
Constructing SubSub
Doin' stuff
One way to achieve this would be to go for a 2 phase construct and initialize. So you construct the instances and then call an initialize method which invoked the base class Initialize in the appropriate order
class MyBase
{
// Only if need to do some core initialization
public MyBase()
{
}
public virtual Initialize()
{
// do some initialization stuff here
}
}
class MyDerived : MyBase
{
// Only if need to do some core initialization
public MyDerived()
{
}
public override Initialize()
{
// do some initialization stuff here
// Call the base class initialization function
base.Initialize();
}
}
public class Parent
{
public Parent()
{
Initialize();
}
protected virtual void Initialize()
{
// do stuff
}
}
public class Child : Parent
{
protected override void Initialize()
{
// do child stuff
base.Initialize();
}
}
There is nothing built into the C# language that lets you do this. However, using a creation pattern could support it. For example, the Abstract Factory pattern might be helpful here. The base factory would ensure that a method is called on the newly created base class once it has been instantiated as the concrete child type.