Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the type of a base class parameter

I have a code like this:

public static void ToUpperCase(params Control[] controls)
{
    foreach (Control oControl in controls)
    {
        if (oControl is TextBox)
        {
            oControl.TextChanged += (sndr, evnt) =>
            {
                TextBox txtControl = sndr as TextBox;
                int pos = txtControl.SelectionStart;
                txtControl.Text = txtControl.Text.ToUpper();
                txtControl.SelectionStart = pos;
            };
        }
        else if (oControl is ComboBox)
        {
            oControl.TextChanged += (sndr, evnt) =>
            {
                ComboBox cmbControl = sndr as ComboBox;
                int pos = cmbControl.SelectionStart;
                cmbControl.Text = cmbControl.Text.ToUpper();
                cmbControl.SelectionStart = pos;
            };
        }
        else throw new NotImplementedException(oControl.GetType().DeclaringType.ToString() + " is not allowed.");
    }
}

I want to limit the params Control[] controls to accept only a TextBox and a ComboBox type.

My code is in C#, framework 4, build in VS2010Pro, the project is in WinForms.

Please help. Thanks in advance.

like image 413
John Isaiah Carmona Avatar asked Dec 12 '22 05:12

John Isaiah Carmona


2 Answers

You can't- they don't have a good common ancestor.

What you can (and probably should) do is make two overloads of your method, which take parameters of each:

public static void ToUpperCase(params TextBox[] controls)
{
    foreach (TextBox oControl in controls)
        oControl.TextChanged += (sndr, evnt) =>
        {
            TextBox txtControl = sndr as TextBox ;
            int pos = txtControl.SelectionStart;
            txtControl.Text = txtControl.Text.ToUpper();
            txtControl.SelectionStart = pos;
        };
}

public static void ToUpperCase(params ComboBox[] controls)
{
    foreach (ComboBoxControl oControl in controls)
        oControl.TextChanged += (sndr, evnt) =>
        {
            ComboBox txtControl = sndr as ComboBox;
            int pos = txtControl.SelectionStart;
            txtControl.Text = txtControl.Text.ToUpper();
            txtControl.SelectionStart = pos;
        };
}
like image 200
Chris Shain Avatar answered Dec 30 '22 09:12

Chris Shain


Normally you should use a common base class for TextBox or ComboBox but that is already Control. Also you cannot change the base classes of those.

The best I can come up with is to add a Debug.Assert to check the type. Something like:

foreach (var control in controls)
    Debug.Assert((control is TextBox) || (control is ComboBox));
like image 45
Michel Keijzers Avatar answered Dec 30 '22 08:12

Michel Keijzers