Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to limit the range of values a property will accept?

I have a user control with some public properties. A particular property is an integer, but must only accept positive values that are less than a const max value. At present I do the following:

private int markerwidth = 2;
[DefaultValue(2), Category("Appearance"), Description("Size of position marker")]
public int MarkerWidth
{
    get
    {
        return this.markerwidth;
    }
    set
    {
        if (value > 0 && value <= MAXMARKERWIDTH)
        {
            this.markerwidth = value;
        }
    }
}

This does the job, but fails silently. I guess I could add logic to use 0 for negative values and the max value for those that exceed it, but it's still not ideal.

By way of contrast, the TabValue property (inherited from UserControl) complains if I try to set a negative value at design time (and presumably at run time).

If this achieved with a normal exception? Or is there a better way? An attribute maybe?

like image 251
Tom Wright Avatar asked Feb 22 '23 14:02

Tom Wright


1 Answers

The most optimal way is to achieve via exception. Just continue your code

    if (value > 0 && value <= MAXMARKERWIDTH)
    {
        this.markerwidth = value;
    }
    else 
    {
        throw new ArgumentOutOfRangeException("Invalid value. Value must be between 0 and " + MAXMARKERWIDTH.ToString());
    }

EDIT

Yes, Wiktor Zychla is absolutely right! I corrected the answer.

like image 72
Oybek Avatar answered May 06 '23 06:05

Oybek