Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  1. Switch to a method for these types.
  2. Change to a collection (ie ICollection<T> or IList<T> implementation)
  3. Turn off this FxCop rule.

Option 3 is always possible, but if we should be doing things differently, then I'd prefer that.

like image 915
Daniel Becroft Avatar asked Sep 11 '11 00:09

Daniel Becroft


1 Answers

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.

like image 135
blowdart Avatar answered Nov 16 '22 19:11

blowdart