Byte transfer [] around

The proxy server created by the third party that we use returns the BLOB data type as byte [], and then we set this value using code generation as follows:

public byte[] FileRawData { get { return internalDataRow.FileRawData; } set { this.internalDataRow.FileRawData = value; } } 

This property is then used in our application (possibly in different assemblies). According to FxCop rules, properties must not expose arrays. So what is the best (or best) approach here? What are others doing in this situation?

  • Go to the method for these types.
  • Modify a collection (i.e., ICollection<T> or IList<T> )
  • Disable this FxCop rule.

Option 3 is always possible, but if we have to do something differently, I would prefer it.

+6
source share
1 answer

A common problem in this situation is immutability. When byte [] is returned, the caller can change it without going through your setter. Think about what happens if someone does

 byte[] retVal = MyInstance.FileRawData; retVal[1] = 0x00; 

Probably not what you want at all, because the value has changed inside MyInstance, which can cause problems. Therefore, to stop the cloning of the array, but it can be potentially time-consuming, and properties should not be used for lengthy operations. The best way to solve this is to switch to methods for sets and get if the array will always be tiny. Of course, when you start writing GetFileRawData () as the name of a method, FXCop will tell you that this should be a property, you cannot win a grin. In this case, just disable it in the code; for this one method.

+2
source

Source: https://habr.com/ru/post/897065/


All Articles