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?
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.
精彩评论