tags:

views:

26

answers:

1

I have a byte array property that must be a certain length. I am tempted to put a check in the property's set block that would throw an ArguementOutOfRange exception if the length is not correct.

private const int MY_ARRAY_LENGTH = 25;
private byte[] m_myArrray;
public byte[] MyArray
{
   get
   {
     return m_myArray
   }
   set
   {
      if (value.Length != MY_ARRAY_LENGTH)
      {
         throw new ArgumentOutOfRange();
      }
      m_myArray = value;
   }

Is that the best practice for this type of bounds checking?

+1  A: 

I see no problem with it. In fact, it certainly seems like the best and most appropriate place to do it since it protects the internal state of your object.

Only trivial change is to perhaps provide more info within the exception (e.g. parameter name - 'value', and the range - 'Length of 25').

Also, I don't have any specific links/frameworks but you may find a declarative style mechanism to automagically handle your argument checks in a consistent way.

Reddog
You should also check that value isn't null.
bbudge
Yes, my ArgumentOutOfRange exception is more flushed out in actual code.
gooch
Sweet article on declarative assertions here http://aabs.wordpress.com/2008/01/16/complex-assertions-using-c-30/
Reddog