patterncsharpCritical
Is it better to return null or empty collection?
Viewed 0 times
emptyreturnbettercollectionnull
Problem
That's kind of a general question (but I'm using C#), what's the best way (best practice), do you return null or empty collection for a method that has a collection as a return type ?
Solution
Empty collection. Always.
This sucks:
It is considered a best practice to NEVER return
When talking about properties, always set your property once and forget it
In .NET 4.6.1, you can condense this quite a lot:
When talking about methods that return enumerables, you can easily return an empty enumerable instead of
Using
This sucks:
if(myInstance.CollectionProperty != null)
{
foreach(var item in myInstance.CollectionProperty)
/* arrgh */
}It is considered a best practice to NEVER return
null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.When talking about properties, always set your property once and forget it
public List Foos {public get; private set;}
public Bar() { Foos = new List(); }In .NET 4.6.1, you can condense this quite a lot:
public List Foos { get; } = new List();When talking about methods that return enumerables, you can easily return an empty enumerable instead of
null...public IEnumerable GetMyFoos()
{
return InnerGetFoos() ?? Enumerable.Empty();
}Using
Enumerable.Empty() can be seen as more efficient than returning, for example, a new empty collection or array.Code Snippets
if(myInstance.CollectionProperty != null)
{
foreach(var item in myInstance.CollectionProperty)
/* arrgh */
}public List<Foo> Foos {public get; private set;}
public Bar() { Foos = new List<Foo>(); }public List<Foo> Foos { get; } = new List<Foo>();public IEnumerable<Foo> GetMyFoos()
{
return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}Context
Stack Overflow Q#1969993, score: 578
Revisions (0)
No revisions yet.