Tom Wright
Tom Wright

Reputation: 11479

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?

Upvotes: 5

Views: 6641

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

There is a builtin ArgumentOutOfRangeException, I guess it fits here.

Upvotes: 2

Oybek
Oybek

Reputation: 7243

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.

Upvotes: 7

Related Questions