What type of collection should be returned from the library instead of an array?

This array is a stream of bytes. The problem with returning only the array is that it is not read-only, and therefore library clients can modify its contents.

There are so many different ways to wrap an array, I'm not sure what to choose:

IEnumerable, IList, List, ReadOnlyCollection, Collection, et cetera.

In addition, the return type may differ from the actual instance type.

My initial approach was to do something like this:

Data = new ReadOnlyCollection<byte>(data);

Where data is an array of bytes. The Data property will have some type of interface (IEnuerable, IList, etc.). However, I am not sure what to use. I see that many recommend IEnumerable, since it is pretty standard, but the order here matters, and the byte stream, in my opinion, should support syntactical similarities to an array. IEnumerable does not allow access to individual indicators, so this is clearly not an optimal choice.

IList is not readonly, so I suppose ICollection will be correct ..? Not sure. It seems that there are so many types of collections, and I'm a little confused about what to use.

+4
source share
3 answers

I would have the desire to return an IList<byte> and document that the list is immutable. This gives you a mixture of the flexibility to change the implementation later, but means that callers do not need to work with the “lowest common denominator” IEnumerable<T> .

Using IList<byte> as the type of declaration, you can still return ReadOnlyCollection<byte> as the implementation.

Or, as Darin mentions, you can use Stream - in particular, MemoryStream :

 return new MemoryStream(data, false); 

This will be a read-only stream. If clients want to read the data as a stream (for example, pass an XML parser or image loader, etc.), that would be better. You would have to declare this as a Stream return - it would be of very little use if I explicitly declare that it returns a MemoryStream (if the caller does not want to call ToArray , of course). You must document that the returned stream is readable, searchable, but not writable.

If they really want to consider it as a collection, IList<T> better.

+2
source

How about directly returning a Stream instead of an array of bytes? Depending on what you expect from customers, which may be related to the results, there may be different approaches. Is it really that bad if they can modify an array of bytes? Even if you return an IEnumerable<T> , they can still call the extension method .ToArray() and get an array of bytes. Therefore, I do not think that changing the byte array in memory due to the consumer should be a problem for you.

+1
source

I would suggest returning a MemoryStream . You can build it so that it is read-only.

+1
source

All Articles