tags:

views:

108

answers:

2

In out program, we have the following class hierarchy:

public class PagePanelBase: UserControl
public sealed class CameraParameters: PagePanelBase

CameraParameters overrides the BackColor property, setting the background color of some of the components it contains. If BackColor is set from the PagePanelBase constructor (InitializeComponent called from there), the CameraParameters constructor hasn't been called yet, so we get a null pointer dereference -- the standard "don't call virtual methods from the constructor" problem.

Now how can we solve this issue? We NEED to use this hierarchy, and we NEED to set the background color from the base class. At present, each deriving class uses a boolean variable "isInitialized" that is set in InitializeComponent, and every overridden method calls InitializeComponent if necessary before doing anything. Is there a better way of doing this? There are already enough broken windows in the code...

+2  A: 

Can you set the background color in an event handler, e.g. OnLoad?

erikkallen
........ or OnInit
Ciwee
That's it! Gotta invest some more time learning the framework, I guess ;) Thanks!
Schmiddy
A: 

Have you tried an abstract method rather than a virtual? Unfortunately, it make not work in your overall hierarchy, but it's worth considering.

Mike Hanson
Abstract and virtual are the same, just that an abstract method needs not have an implementation. Regarding calling them from a constructor, though, they are equivalent.
erikkallen
I had a feeling. <g>
Mike Hanson