Green Textboxes and c# esotericness
Lets say you wanted to make a textbox that was really ugly. So, hey, lets make the BackColor green. That's plenty ugly. So you do this:
public class UglyTextBox : TextBox {
public override Color BackColor {
get { return Color.Green; }
set { }
}
}
Then you realize, that hey, somebody using my control might think of an even UGLIER backcolor, so you just want to make it the default BackColor, so you quickly change it to this:
public class UglyTextBox : TextBox {
public UglyTextBox() {
BackColor = Color.Green;
}
}
Little do you realize, you've actually commited a c# sin. Thou Shalt Not Call Virtual Members From The Constructor. The reason for this is explained fairly well in this develop.com thread. Basicly, things go bad if a subclass overrides the virtual method you call in the constructor, and uses variables created in its constructor, because your constructor is called before its constructor. So, you might think you can do this:
public class UglyTextBox : TextBox {
protected override void OnInit(EventArgs e) {
BackColor = Color.Green;
base.OnInit(e);
}
}
And while this will work at runtime, it won't work at design time. The Init event doesn't happen in the designer. None of the events do. The controls are simply constructed, properties from the tag are set, and then hit RenderControl. So for full design time support of a change in default property value, this is the best solution I've come up with so far:
public class UglyTextBox : TextBox {
[DefaultValue(typeof(Color),"Green")]
public override Color BackColor {
get {
if ( BackColorSet ) {
return base.BackColor;
}
return Color.Green;
}
set {
BackColorSet = true;
base.BackColor = value;
}
}
private Boolean BackColorSet = false;
}
Meh. Does that seem overly complicated to anybody else?