Passing a byte[] around
A third-party generated proxy that we use exposed the BLOB data type as a byte[], and we then expose this value through code generation as follows:
public byte[] FileRawData
{
get { return internalDataRow.FileRawData; }
set { this.internalDataRow.FileRawData = value; }
}
This property is then used througout our application (potentially in different assemblies). According to the FxCop rules, properties shouldn't be exposing arrays. So, what's the better (or best) approach here? What do others do in this situation?
- Switch to a method for these types.
- Change to a coll开发者_如何学Pythonection (ie
ICollection<T>
orIList<T>
implementation) - Turn off this FxCop rule.
Option 3 is always possible, but if we should be doing things differently, then I'd prefer that.
The usual problem in this sort of situation is immutability. When the byte[] gets returned the caller can change it, without go through your setter. Consider what happens if someone did
byte[] retVal = MyInstance.FileRawData;
retVal[1] = 0x00;
Probably not what you want at all, because the value has changed inside MyInstance, which could cause problems. So in order to stop that you clone the array, but that can be potentially long running, and properties shouldn't be used for long running operations. Best way to solve it is switch to methods for sets and gets, unless the array is always going to be tiny. Of course when you start writing GetFileRawData() as a method name FXCop will prompt you that it should be a property, you can't win grin In that case just disable it in code; for that one method.
精彩评论