.NET API Documentation

Namespace: System.Linq

Enumerable.Empty<T> Method

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

Description

Returns an empty enumerable collection of the specified type. This method is useful for returning an empty result without creating a new object.

Remarks

The returned enumerable is stateless and can be reused. It does not allocate any resources or memory beyond what is necessary to represent an empty collection.

This method is generally preferred over creating an empty generic list (e.g., new List<T>()) when you simply need to represent an empty sequence, as it can be more efficient.

Type Parameters

  • T: The type of the elements in the enumerable collection.

Return Value

An empty IEnumerable<T>.

Example

The following example demonstrates how to use the Empty<T> method to get an empty list of strings.

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

public class Example
{
    public static void Main(string[] args)
    {
        // Get an empty enumerable of strings
        IEnumerable<string> emptyStrings = Enumerable.Empty<string>();

        // You can perform LINQ operations on it, though they will have no effect
        var count = emptyStrings.Count(); // count will be 0
        Console.WriteLine($"Count: {count}");

        // You can iterate over it, but the loop body will never execute
        foreach (var str in emptyStrings)
        {
            Console.WriteLine(str); // This line will never be reached
        }

        // Get an empty enumerable of integers
        IEnumerable<int> emptyIntegers = Enumerable.Empty<int>();
        Console.WriteLine($"Is empty: {emptyIntegers.Any() == false}");
    }
}