Search code examples
c#app-configconfiguration-management

Is it a good way to test value in property getters / setters of ConfigurationElement


Here is what I've written to test values of the app.config file of my application and I want to know if it's a good way ? I throw an ArgumentOutOfRangeException directly in the MyProperty getters/setters:

internal sealed class ProcessingMyPropertyElement : ConfigurationElement
{
    [ConfigurationProperty("myproperty", IsRequired = true)]
    public int MyProperty
    {
        get
        {
            if ((int)this["myproperty"] < 0 || (int)this["myproperty"] > 999)
                throw new ArgumentOutOfRangeException("myproperty");

            return (int)this["myproperty"];
        }
        set
        {
            if (value < 0 || value > 999)
                throw new ArgumentOutOfRangeException("myproperty");

            this["recurEvery"] = value;
        }
    }
 }

Solution

  • When setting the value it is a good idea to check for the range and throw an exception when this is invalid.

    On getting it, I wouldn't throw an exception. This way someone could crash the application by editing the app.config by hand. In your getter I would limit the value to the specific range and return a valid result.

    if ((int)this["myproperty"] < 0 )
    {
         return 0;
    }
    
    if ((int)this["myproperty"] > 999 )
    {
         return 999;
    }
    
    return (int)this["myproperty"]