Reputation: 90912
Given a superclass which I cannot change which defines a certain property, how am I best to set the default value of it in a subclass?
Say, for example, that I am subclassing System.Windows.Forms.ToolStripButton
and want to set a default value for the Text
property. (For a more complex example, I also want to define the click handler, e.g.
Click += new EventHandler(click)
.) How am I best to do that?
Some ideas that I have had:
Set it in the constructor. But with multiple constructors, is that feasible? (I haven't got a firm grasp on how the constructors play with one another yet. Can I just update one and have them all Just Work™?)
Set it as a field, i.e. public string Text = "foo";
as I expected, this doesn't work.
Always call a certain method to set these values (I might name it, for example, InitializeComponent
).
Ideally, I would be subclassing this class further and would be wanting to define the default values in it. I guess for that side I'd have protected fields and have the constructor or method read those values and assign them.
Is there some other way that hasn't occurred to me?
Or does my design not seem the right way around? I could also use a different class and work with a ToolStripButton
instance inside it—aggregation rather than inheritance. (The more I think about this, the more it feels like it might be the right answer.)
It's the sort of thing that I know precisely how to do in Python, but doesn't look likely to be very elegant in C# (I know: different styles of language, tradeoffs, etc.; I'm not criticising C#).
Upvotes: 2
Views: 1402
Reputation: 1064244
Constuctor is probably the easiest route. You can always daisy-chain the constructors if it is a problem, for example:
public Foo() : this(12, "abc") {}
public Foo(int bar, string name) {
this.bar = bar;
this.name = name;
}
The other option is explicit properties (not auto-props) and field initialisers:
private int bar = 12;
public int Bar {
get { return bar; }
set { bar = value; }
}
In either case, you should consider adding [DefaultValue(...)]
to the property, so that bindings (UI, serializers, etc) know about it. In this case, [DefaultValue(12)]
.
Upvotes: 2