views:

132

answers:

2

I have an abstract base class which inherits from UserControl and which is then used to derive a number of classes.

The problem I have is how to elegantly ensure that the generated function InitializeComponent() is called for each layer of class.

So the (abstract) base class has a number of controls on it that will be shared for all children. When creating an instance of the child class, the base constructor is called first, but is there any way to elegantly call the derived InitializeComponent() without having to build effectively the same Constructor for each derived class

public DerivedClass() { 
  InitializeComponent();
}

I'm wondering if there's a more efficient way than repeating myself in each Derived class?

In effect, I'd like the (abstract) base class to be able to called

Derived.InitializeComponent();

After all, when it's in the base constructor (in debug) it knows that it's a derived instance ...

+1  A: 

public DerivedClass() : base() {}

This will call your base constructor, there isn't usually a magic way to do things, if you need InitializeComponents called, you'll probably have to call it yourself.

Nick
A: 

if you make InitializeComponent virtual, and you override it for all sub-classes, the base class will call the right method for each of the sub-classes if you call the base constructor from the derived constructor.

MrJavaGuy
A little dangerous... the base class constructor will call the most derived virtual implementation. This means that subclasses' `InitializeComponent` methods will get called before the subclasses' constructors themselves -- a timebomb for anyone adding logic into the subclass constructors.
Tim Robinson