1
\$\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;
 }
}
asked Feb 27, 2021 at 9:48
\$\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\$ Commented Feb 27, 2021 at 10:28
  • \$\begingroup\$ You can use AOP if you want to add elegant validation. \$\endgroup\$ Commented Feb 27, 2021 at 10:37

1 Answer 1

3
\$\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;
 }
}
answered Feb 27, 2021 at 10:31
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.