Is it possible to make attribute which can limit minimum or maximum value of numbers.
Example:
[MinValue(1), MaxValue(50)]
public int Size { get; set
You can elegantly solve this problem by using PostSharp by writing simple aspect, free version will be enough for this purpose:
[Serializable]
class RangeAttribute : LocationInterceptionAspect
{
private int min;
private int max;
public RangeAttribute(int min, int max)
{
this.min = min;
this.max = max;
}
public override void OnSetValue(LocationInterceptionArgs args)
{
int value = (int)args.Value;
if (value < min) value = min;
if (value > max) value = max;
args.SetNewValue(value);
}
}
and then exacly as you want:
class SomeClass
{
[Range(1, 50)]
public int Size { get; set; }
}
with normal usage:
var c = new SomeClass();
c.Size = -3;
Console.Output(c.Size);
will output 1.