Reputation: 11828
The array in question is a stream of bytes. The problem with returning just an array is that it is not read-only and thus the clients of the library can modify its contents.
There are so many different ways of wrapping the array I'm not sure which to choose:
IEnumerable, IList, List, ReadOnlyCollection, Collection, et cetera.
Also, the return type can be different from the actual instantiated type.
My initial approach was to do something like this:
Data = new ReadOnlyCollection<byte>(data);
Where data
is a byte array. The Data property would be of some interface type (IEnuerable, IList, et cetera.) However, I'm not sure which to use. I see many recommend IEnumerable as it is pretty standard but order matters here and a stream of bytes, in my opinion, should maintain syntactical similarities to an array. IEnumerable does not allow accessing of individual indicies so it is obviously not the optimal choice here.
IList is not readonly so I suppose ICollection would be correct..? Not sure really. There seem to be so many collection types and I'm getting a bit confused as to which to use.
Upvotes: 4
Views: 161
Reputation: 134055
I would suggest returning a MemoryStream
. You can construct it so that it's read-only.
Upvotes: 1
Reputation: 1502546
I would be tempted to return IList<byte>
and document that the list is immutable. That provides you with a mixture of the flexiblity of changing the implementation later on, but means that callers don't need to work with the "lowest common denominator" of IEnumerable<T>
.
Using IList<byte>
as the declaration type you can still return a ReadOnlyCollection<byte>
as the implementation.
Or as Darin mentions, you can use a Stream
- in particular, a MemoryStream
:
return new MemoryStream(data, false);
That will be a read-only stream. If clients want to read the data as a stream (e.g. to pass to an XML parser or image loader etc) then that would be best. You'd only need to declare it as returning Stream
- there'd be very little benefit in explicitly declaring that it returns MemoryStream
(unless the caller wants to call ToArray
, of course). You should document that the returned stream is readable, seekable, but not writable.
If they actually want to treat it as a collection, IList<T>
is better.
Upvotes: 2
Reputation: 1039248
How about directly returning a Stream
instead of an array of bytes? Depending on what do you expect the clients to be able to do with the results there might be different approaches. Is it really so bad if they can modify the array of bytes? Even if you return an IEnumerable<T>
they can still call the .ToArray()
extension method and get an array of bytes. So I don't think that modifying an in-memory array of bytes from the consumer should be a problem for you.
Upvotes: 1