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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With