C# DefaultIfEmpty Method

LINQ (language integrated query)

You want to change a collection that is empty to one that has one element. With DefaultIfEmpty, we can replace empty collections with a singleton collection that may be more compatible with other parts of your C# program.

This C# tutorial shows how to use the DefaultIfEmpty extension method from System.Linq.

Example

The concept of DefaultIfEmpty is simple: it will replace an empty collection with a collection that contains one default value. Remember that the default value of an int is 0. Thus, DefaultOrEmpty on a List<int> will yield a List with one zero element.

List Examples
Program that uses DefaultIfEmpty [C#]

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

class Program
{
    static void Main()
    {
	// Empty list.
	List<int> list = new List<int>();
	var result = list.DefaultIfEmpty();

	// One element in collection with default(int) value.
	foreach (var value in result)
	{
	    Console.WriteLine(value);
	}

	result = list.DefaultIfEmpty(-1);

	// One element in collection with -1 value.
	foreach (var value in result)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

0
-1

DefaultIfEmpty with argument. You can pass an argument to DefaultIfEmpty. This will become the value that is used in the singleton collection's value. Please see the next section for discussion about this functionality.

Usage

Refactoring

If you call DefaultIfEmpty on a null reference, you will get a NullReferenceException. This means that DefaultIfEmpty can only be used to handle empty collections. Conceptually, the method is useful if in other locations in your program, empty collections cannot be used.

Null Tips NullReferenceException and Null Parameter

The version of DefaultIfEmpty that receives an argument may actually be more useful. This means you can use a custom default object that has special behavior. In the book Refactoring, this technique is referred to as a null object (see Introduce Null Object). You could pass a reference to the null object to DefaultIfEmpty; then methods can act upon the objects in the collection without knowing about empty collections.

Refactoring Book Review

Summary

We saw the behavior of the DefaultIfEmpty method on an empty List collection. The method can be used to change empty collections to collections with one element. With the optional parameter, you can use custom default objects that can have special behavior for the collection.

LINQ Examples
.NET