开发者

FxCop says I should return a generic list inteface instead of a byte array. Should I? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it 开发者_如何学Ccan be answered with facts and citations by editing this post.

Closed 7 years ago.

Improve this question

I'm writing a library and instead of returning a byte array from an EventArgs derivation, it says I should return something like IList or ReadOnlyCollection instead.

Normally I'd be all for this but most of the existing .NET Framework uses byte arrays as opposed to generic list interfaces.

So if I were to use IList then when accessing the eventargs, if a client wanted to call File.WriteAllBytes he or she would have to do using System.Linq; and call the ToArray extension method to get the IList in the form of an array of bytes. Of course there are other ways to do this but this is the most elegant and typical.

Clients of this library are always going to want things to be in terms of an array of bytes so that they interface nicely with the rest of the framework.

Also, optimization may come in to play here. There is potential for large amounts of bytes to be manipulated so having to recopy the entire list just to get it in the form of a byte array each time would likely slow things down.

Lastly, it's just plain unpleasant. If clients are always going to want a byte array, then why not just give it to them? Do framework design guidelines not apply in this situation? What would you do?


There is potential for large amounts of bytes to be manipulated so having to recopy the entire list just to get it in the form of a byte array each time would likely slow things down.

But that is precisely why it should not be a byte array. Suppose you do this:

byte[] x1 = GetByteArray();
x1[0] = 0;
byte[] x2 = GetByteArray();

Every time you call GetByteArray you have to create a new byte array. Why? Because someone might have changed the one you handed out last time to have different contents! By handing out a byte array you guarantee that you are going to have to reconstruct that byte array from scratch every single time.

By contrast, if you hand out a read only collection of bytes then you can hand out the same collection over and over again. You know it is not going to change.


Clients of this library are always going to want things to be in terms of an array of bytes so that they interface nicely with the rest of the framework.

There you have your answer - FxCop output is in most cases just helpful suggestions - not commands - if this particular one doesn't apply to you you can even turn it off.


The guidelines and recommendations offered by FxCop are not always applicable in every situation. You don't need to follow them, and in some situations you shouldn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜