Should I return empty or nullable array?

I have a public method which searches for an image and if the image exists, it returns it as a byte array.

What the method should return, if the image doesn't exist? (the image not existing is not an exception, but expected possibility)

Should I return an empty byte[] array, or should it return byte?[] set to null instead?

Which one is more in tune with conventions?

Jon Skeet
people
quotationmark

I would return null (just as a byte[] - all arrays are reference types). Returning an empty array will lead the caller to think they can try to load that data as an image - which they can't. Returning a null reference makes it very easy to differentiate between "present and empty" vs "not present at all".

In other cases where the image being missing is an indication of a significant system problem, I'd consider an exception though. It sounds like that's not the case here.

Note that this is significantly different to a normal method returning a collection of individual elements - you don't care about each byte as a separate entity in the way that you would for a method returning List<Person> for example; here the byte[] is effectively a blob. I would regard it as a single chunk of data which happens to be represented as an array rather than a collection. To put it another way: think about it as if your method were declared to return a Blob type instead of an array... would you return a null reference, or an instance of Blob with no data?

people

See more on this question at Stackoverflow