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; }
and when i do Size = -3;
value of Size
must be 1.
I searched in Google and can't find single example about this behavior, maybe because it is not possible to make?
I'm gonna use these attributes in property grid therefore having automatic validation can be handy.
Currently I workaround like this to limit minimum value:
private int size;
[DefaultValue(8)]
public int Size
{
get
{
return size;
}
set
{
size = Math.Max(value, 1);
}
}
So this acts like MinValue(1)
MinValue defines the date and time that is assigned to an uninitialized DateTime variable.
The MinValue property or Field of Int32 Struct is used to represent the minimum possible value of Int32. The value of this field is constant means that a user cannot change the value of this field. The value of this field is -2,147,483,648.
Represents the smallest possible value of an Int64. This field is constant. public: long MinValue = -9223372036854775808; C# Copy.
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.
Although it is possible to create a custom attribute, attributes are just metadata for the member they annotate, and cannot change its behavior.
So, you won't get the behavior you want with a plain attribute. You need something to process the attributes in order to enact the desired behavior.
Take a look at TypeConverters for a possibility.
Yes, it is possible. Read about custom attributes at MSDN.
And by the way, there is already a solution you can use. It is the RangeAttribute
which lets you specify the numeric range constraints for the value of a data field. Read more about it on MSDN.
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