Davide Andrea
Davide Andrea

Reputation: 1413

Multiple custom controls all using the same properties; is an interface the most elegant way to get a property?

I have multiple custom controls (inheriting from TextBox, NumericUpDown, etc.), each of which has a property MaxValue.

I iterate through a list of all the custom controls in a form, getting the MaxValue for each control, regardless of the Type of the control.

I could go through each Type of control, see if a given control is of that type, cast the control to that type, and get its MaxValue.

if (aControl is ConfigTextBox) {maxValue = ((ConfigTextBox)aControl).MaxValue;}
if (aControl is ConfigNumericUpDown) {maxValue = ((ConfigNumericUpDown)aControl).MaxValue;}
etc...

It would be cleaner not to need to look at each type, and do it in a single line:

float maxValue = aControl.MaxValue;

I solved this awkwardly by using an interface; The interface defines methods to get the properties of each custom control. Therefore, each custom control has to define both a field and a method for each property.

This is ugly.

(Note: the methods add an underscore to the field name, to keep the 2 distinguished.)

The interface:

interface ConfigControl
{
     float MaxValue_();   
     ...(more methods, one per property)
}

One of the custom controls:

public partial class ConfigTextBox : TextBox, ConfigControl
{
    private float maxValue = 10;
    ....
    // Maximum
    [DefaultValueAttribute(10), Description("The maximum value that can be entered in this setting"), Category("Data")]
    public float MaxValue
    {
       get { return maxValue; }
       set { maxValue = value; }
    }
    public float MaxValue_() { return maxValue; }
    .... (more properties)
}

Another one of the custom controls:

public partial class ConfigNumericUpDown : NumericUpDown, ConfigControl
{
    private float maxValue = 10;
    ....
    // Maximum
    [DefaultValueAttribute(10), Description("The maximum value that can be entered in this setting"), Category("Data")]
    public float MaxValue
    {
       get { return maxValue; }
       set { maxValue = value; }
    }
    public float MaxValue_() { return maxValue; }
    .... (more properties)
}

Getting the max value:

float maxValue = ((ConfigControl)aControl).MaxValue_();

My questions:

Upvotes: 2

Views: 412

Answers (1)

Anthony
Anthony

Reputation: 9571

It seems to me that you aren't aware you can define an interface with a property getter:

interface ConfigControl
{
     float MaxValue { get; }
}

If you define your interface this way, than any class implementing the interface must have at least the get part of the MaxValue property. Since it seems all your custom controls have this property then you shouldn't need to do anything else - no MaxValue_() methods needed.

Upvotes: 2

Related Questions