Chris Morgan
Chris Morgan

Reputation: 90912

How should I set the default value of a property in a subclass?

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:

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

Answers (1)

Marc Gravell
Marc Gravell

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

Related Questions