The LINQ Empty Method in C# is a static method included in the static Enumerable class. The Empty Method is used to return an empty collection (i.e. IEnumerable<T>) of a specified type. The following is the signature of this method.

Here TResult specifies the type parameter of the returned generic IEnumerable<TResult>. This method returns an empty IEnumerable<TResult> whose type argument is TResult.

 

Example 1: Understand LINQ Empty Method in C#:

Let us see an example to understand LINQ Empty Method in C#. In the following example, we have created two empty collections using the LINQ Empty Method. The first Empty method returns an empty collection of strings while the second Empty method returns an empty collection of students.

Why do we need LINQ Empty Method in C#?

Let us understand the need for LINQ Empty Method in C# with an example. Consider one scenario, where our application calls a method that returns an IEnumerable<int>. There might be a situation where the method returns null. In the following example, the GetData() method is returning null. So, when we run the following program, it will throw a NULL Reference Exception.

So, when you run the above code, you will get the following Runtime Exception.

Why do we need LINQ Empty Method in C#

The above problem can be fixed in two ways.

 
Solution1: Checking Null Before using inside the Loop

We need to check for NULL before looping through the items in the collection as shown in the below example.

 

Solution2: Using the LINQ Empty Method

We can solve the problem by using the LINQ Empty Method as shown in the below example. Here, we are using the NULL-COALESCING operator which checks if the GetData() method returns NULL, then initialized the integerSequence variable with an empty IEnumerable<int>.

Note: The main advantage of using the Empty method is “Even if you use an empty array or empty collection, then those are objects. As objects, they are going to be stored in the memory. Once they are stored in memory, then it is the responsibility of the Garbage Collector to take care of them”.

In the next article, I am going to discuss the Linq Append Method in C# with Examples. Here, in this article, I try to explain the LINQ Empty Method in C# with Examples. I hope you enjoy this article.

Leave a Comment