.NET Docs

System.Linq.Enumerable.Empty<T>

Represents an empty sequence. This property can be used to return an empty enumerable of a specified type, avoiding the creation of a new empty enumerable object each time.

public static IEnumerable<TResult> Empty<TResult>()

Parameters

This method does not take any parameters.

Return Value

An IEnumerable<TResult> that returns zero elements. The cached instance is used for all calls to Enumerable.Empty<TResult>.

Remarks

The Enumerable.Empty<TResult> method is useful for returning an empty collection when a method is expected to return an enumerable. For example, if you have a method that returns a list of items, but sometimes there are no items to return, you can return Enumerable.Empty<T> to represent the empty list.

This method returns a singleton instance of an empty enumerable. This means that all calls to Enumerable.Empty<TResult> for a given type TResult will return the same object. This can be beneficial for performance, as it avoids the overhead of creating a new empty enumerable object each time.

Note: The returned sequence is immutable and cannot be modified.

Example

The following example demonstrates how to use the Enumerable.Empty<T> method to return an empty list of integers.

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
public static IEnumerable<int> GetNumbers(bool includeNumbers)
{
if (includeNumbers)
{
return new List<int> { 1, 2, 3 };
}
else
{
return Enumerable.Empty<int>();
}
}

public static void Main(string[] args)
{
IEnumerable<int> numbers1 = GetNumbers(true);
Console.WriteLine($"Numbers 1 count: {numbers1.Count()}"); // Output: Numbers 1 count: 3

IEnumerable<int> numbers2 = GetNumbers(false);
Console.WriteLine($"Numbers 2 count: {numbers2.Count()}"); // Output: Numbers 2 count: 0
}
}

See Also