Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return 'null' or an empty array?

Suppose you have a method that should create and return an array of some sort. What if the array doesn't get populated. Do you return an empty array or null/nothing?

like image 798
Gargamel Avatar asked Dec 01 '08 21:12

Gargamel


People also ask

Is it better to return null or empty string?

Returning null is usually the best idea if you intend to indicate that no data is available. An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Is it good practice to return null?

Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.

IS null an empty array?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.

Is null the same as empty list?

An empty collection isn't the same as null . An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.


Video Answer


2 Answers

In .NET it's better to return an empty array than null because it saves the caller having to write a null check and/or risking a NullReferenceException; you'll see this is a common pattern in the base class libraries. The only case in which you wouldn't do this is in the unlikely scenario that an empty array and null have different semantic meanings.

The official array usage guidelines state:

The general rule is that null, empty string (""), and empty (0 item) arrays should be treated the same way. Return an empty array instead of a null reference.

That said, if you're using .NET 2.0 or later, it's much better to return an IEnumerable<T> or one of its extensible derivatives such as Collection<T>, ReadOnlyCollection<T>, ICollection<T> or IList<T> (in which case I'd still tend to return an empty one instead of null). More info as to why these should be preferred can be found at Eric Lippert's blog.

like image 165
Greg Beech Avatar answered Sep 25 '22 02:09

Greg Beech


I return an empty array - just seems like the right thing to do.

like image 20
Patrick Harrington Avatar answered Sep 26 '22 02:09

Patrick Harrington