views:

170

answers:

2

i am creating a usercontrol which provides all of the common validations for a range of textbox styles: alpha, number, decimal, SSN, etc. so, when a developer using this control selects the alpha style, they can also select another property which defines a string of special characters that could also be allowed during validation.

but when the decimal style, for instance, is selected, i'd like to simply disable the special characters property so it is not settable when a style is selected that doesn't allow special characters.

how can i achieve this goal?

thanks

A: 

I would consider doing it in the setter of the properties

private string specialCharacters = "";
public string SpecialCharacters
{
   get { if ( usingDecimals ) 
           specialCharacters = "";

        return specialCharacters; }

   set { if( usingDecimals )
            value = "";

         specialCharacters = value; }
}

private boolean usingDecimals = false;
public boolean UsingDecimals
{  get { return usingDecimals; } 
   set { usingDecimals = value;
         if( usingDecimals )
             specialCharacters = ""; }
}
DRapp
+2  A: 

You can't disable properties in C# - they're part of your type's interface, which promises that callers can bind to those operations at compile-time.

The simplest implementation is to ignore the special characters when the user specifies an incompatible style. This is idiomatic .NET behavior - for example, see the CompareValidator, which has some mutually exclusive properties:

Do not set both the ControlToCompare and the ValueToCompare property at the same time. You can either compare the value of an input control to another input control, or to a constant value. If both properties are set, the ControlToCompare property takes precedence.

Having said that, this technique makes classes harder to use than they need to be - their interfaces don't really tell you how to use them. I recommend breaking your validator into two classes: one for alphabetic validations and one for numeric validations.

Alternately, you can throw an exception in your setter when the style doesn't support special characters. Often, that's too drastic, but it makes it clear to the client programmer that they've done something invalid.

Jeff Sternal