Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MinValue & MaxValue attribute for properties

Tags:

c#

attributes

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)

like image 207
Jaex Avatar asked Nov 16 '13 13:11

Jaex


People also ask

What is MinValue?

MinValue defines the date and time that is assigned to an uninitialized DateTime variable.

What is int MinValue in C#?

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.

What is long MinValue?

Represents the smallest possible value of an Int64. This field is constant. public: long MinValue = -9223372036854775808; C# Copy.

What is the default DateTime value in C#?

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.


2 Answers

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.

like image 66
Jordão Avatar answered Oct 06 '22 16:10

Jordão


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.

like image 3
Ondrej Janacek Avatar answered Oct 06 '22 16:10

Ondrej Janacek