0
\$\begingroup\$

I have some classes with properties, wich could only have numeric values in a given range (e.g. 0 to 8). This should be validated and wrong values prevented with an exception. The given behavior may be implemented without duplicating the given code.

There are some ValidatorAttributes in C# but I can't get them to running. They don't seem to prevent the assignment with wrong values in a normal class.

My current solution is to copy paste this snippet for every attribute. But copy paste is not perfect:

private short _index;
public short Index
{
    get => this._index;
    private set
    {
        const short min = 0;
        const short max = 8;
        if (value < min || max < value)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
        this._index = value;
    }
}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ The attribute itself does not execute any code. A certain engine must use the code described in this attribute. The attribute you mentioned is used by the configuration engine. And, for example, this Range attribute is used by the ASP.NET engine. \$\endgroup\$ – Alexander Petrov Feb 27 at 10:28
  • \$\begingroup\$ You can use AOP if you want to add elegant validation. \$\endgroup\$ – Alexander Petrov Feb 27 at 10:37
2
\$\begingroup\$

To reduce the lines of code to copy/paste, you could create a helper method:

public static class Helper
{
    public static void EnsureIsInRange(short value, short min, short max)
    {
        if (value < min || max < value)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
    }
}

or more generic:

public static class Helper
{
    public static void EnsureIsInRange<T>(T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) != 1 || value.CompareTo(max) != -1)
        {
            throw new ArgumentOutOfRangeException("The passed value is not between " + min + "  and " + max + " (values included)");
        }
    }
}

// usage:

private short _index;
public short Index
{
    get => this._index;
    private set
    {
        Helper.EnsureIsInRange(value, 0, 8);
        this._index = value;
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you for your help. It thats what I need. \$\endgroup\$ – finder2 Feb 27 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.