tags:

views:

114

answers:

2

If I have a method or a property that returns an IEnumerable<SomeType> that leads to no data, is it more efficient to return an empty array new SomeType[0] or is it better to return an empty list new List<SomeType>() or is there an even better solution (IMO building an own type with generics could be such a solution but it seems to me a little bit overkill)?

The array is my favorite but what do you think about this?

+15  A: 

Return Enumerable.Empty<T>().

Mehrdad Afshari
Better than creating a new object everytime the property is called.
Adrian Godong
I still find it strange that it is Enumerable.Empty<T>() rather than Enumerable<T>.Empty().
spender
Maybe if it were "Enumerable<T>.Empty()" then the class constructor for Enumerable<T> would be called for each Type that is used (if not already initialized) and with "Enumerable.Empty<T>()" this could be prevented (only an idea, I don't have any profound knowledge of generics).
HCL
A: 

Two ideas:

IEnumerable<SomeType> returnedValue = SomeProperty;
if (returnedValue == null)
{
     //it means it's empty
}

Or it can be done, like Mehrdad Afshari said to return Enumerable.Empty<T>().

virious
This is a **very bad idea**. Do **not** use null to represent an empty sequence; if you do so then you are building a little bomb that will go off unexpectedly when someone says, oh, I see this thing implements IEnumerable, I can "foreach" over it. But foreach does not check to see if the sequence is null, it just crashes. **Always represent an empty sequence as an empty sequence.** Use null only to represent a *missing* or *erroneous* sequence.
Eric Lippert