Return empty List<T> or null when no list items present?
I'd definitely return an empty list so methods can still be called on the object without requiring null checks. There's a difference between returning an empty list and returning nothing at all, so the calling code probably isn't expecting to receive a null reference anyway (unless an exception occurs or something).
It depends on a number of factors, but an empty list would be a more typical return value, as otherwise the caller must know to perform null
checking. The main time I'd return a null
is if it was a method of this style:
bool Try*(args, out result)
The caller expects (on receiving false
) not to even look at the value of result
.
If you happen to be returning arrays, there is a nice cheat - you can store a zero-length typed array in a static field somewhere are return that. But ultimately an empty list isn't going to be a huge overhead to allocate, so just sent that.
An empty list is what I'd expect as a caller. Null would indicate to me that the "conceptual list" is undefined, like null in a database.
Also, by always returning empty collections rather than null, clients like these will never fail:
foreach(var element in obj.Method()) ...