C# Program to Demonstrate DefaultIfEmpty Method – Programming, Pseudocode Example, C# Programming Example
C# C# Console C# LINQ Examples

C# Program to Demonstrate DefaultIfEmpty Method

DefaultIfEmpty is a LINQ method that is used to return a default value if a sequence is empty, or the original sequence if it is not empty. It is defined in the System.Linq namespace and is a member of the Enumerable class.

The DefaultIfEmpty method takes a single parameter of the same type as the elements in the sequence. This parameter specifies the default value to return if the input sequence is empty. If the input sequence is not empty, DefaultIfEmpty returns the original sequence.

Here is the syntax for the DefaultIfEmpty method:

The DefaultIfEmpty method returns an IEnumerable<TSource> sequence that contains the default value if the input sequence is empty, or the original sequence if it is not empty.

Here is an example of how to use the DefaultIfEmpty method:

In this example, the input sequence is not empty, so DefaultIfEmpty returns the same sequence.

In this example, the input sequence is empty, so DefaultIfEmpty returns a singleton sequence that contains the default value of 0.


Here is an example of a C# program that demonstrates the use of the DefaultIfEmpty method:

This program will output the following:

The DefaultIfEmpty method returns a singleton sequence that contains the default value of the type if the input sequence is empty, or the input sequence if it is not empty. In this example, the default value for integers is 0. If the input array is empty, DefaultIfEmpty returns a singleton sequence that contains the default value of 0. If the input array is not empty, DefaultIfEmpty returns the same array.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.