optimize integer validation 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 =&gt; this._index;
    private set
    {
        const short min = 0;
        const short max = 8;
        if (value &lt; min || max &lt; value)
        {
            throw new ArgumentOutOfRangeException(&quot;The passed value is not between &quot; + min + &quot;  and &quot; + max + &quot; (values included)&quot;);
        }
        this._index = value;
    }
}
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 &lt; min || max &lt; value)
        {
            throw new ArgumentOutOfRangeException(&quot;The passed value is not between &quot; + min + &quot;  and &quot; + max + &quot; (values included)&quot;);
        }
    }
}

or more generic:
public static class Helper
{
    public static void EnsureIsInRange&lt;T&gt;(T value, T min, T max) where T : IComparable&lt;T&gt;
    {
        if (value.CompareTo(min) != 1 || value.CompareTo(max) != -1)
        {
            throw new ArgumentOutOfRangeException(&quot;The passed value is not between &quot; + min + &quot;  and &quot; + max + &quot; (values included)&quot;);
        }
    }
}

// usage:
private short _index;
public short Index
{
    get =&gt; this._index;
    private set
    {
        Helper.EnsureIsInRange(value, 0, 8);
        this._index = value;
    }
}