c# – Is it better to return null, or an empty collection?

Question:

If the return type is a collection, is it better to return null or an empty collection? Is there a common practice?

A similar question on en.SO: Is it better to return null or empty collection?

Answer:

The question here is semantics.

When asked "give me a list of all users", an empty collection has the obvious meaning: "OK, here's a list of all users, there are exactly 0 of them."

On the other hand, the returned null can mean anything: “I don’t know how many users”, “the number of users has not been counted yet”, “the current database has no concept of _user_ at all”, whatever.

The meaning of an empty collection is always clear, the meaning of null is undefined.

Related article: Eric Lippert, Null Is Not Empty .

Scroll to Top