LINQ Empty Method in C#

LINQ Empty Method in C# with Examples

In this article, I am going to discuss the LINQ Empty Method in C# with Examples. Please read our previous article where we discussed the LINQ Repeat Method in C# with Examples. Like the LINQ Range and Repeat Methods, the Empty method also belongs to the Generation Operator Category. As we already discussed, Generation Operators allow us to create some specific type of Array, Sequence, or Collection using a single expression instead of creating and populating them manually using some kind of loop. 

LINQ Empty Method in C#: 

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.

Linq Empty Method in C# with Examples

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 to Understand 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.

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

namespace LinqDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating Empty Collection of Strings
            IEnumerable<string> emptyCollection1 = Enumerable.Empty<string>();

            //Creating Empty Collection of Student
            IEnumerable<Student> emptyCollection2 = Enumerable.Empty<Student>();

            //Printing the Type and Count of emptyCollection1
            Console.WriteLine("Count: {0} ", emptyCollection1.Count());
            Console.WriteLine("Type: {0} ", emptyCollection1.GetType().Name);

            //Printing the Type and Count of emptyCollection2
            Console.WriteLine("Count: {0} ", emptyCollection2.Count());
            Console.WriteLine("Type: {0} ", emptyCollection2.GetType().Name);

            Console.ReadKey();
        }
    }

    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
Output:

Example to Understand LINQ Empty Method in C#

Why do we need 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.

using System.Collections.Generic;
using System;
namespace LinqDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //GetData() Method Returning Null
            IEnumerable<int> integerSequence = GetData();

            //The forloop will throw NullReferenceException
            foreach (var num in integerSequence)
            {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }

        private static IEnumerable<int> GetData()
        {
            return null;
        }
    }
}

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.

using System.Collections.Generic;
using System;
namespace LinqDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> integerSequence = GetData();
            if(integerSequence != null)
            {
                foreach (var num in integerSequence)
                {
                    Console.WriteLine(num);
                }
            }           
            Console.ReadKey();
        }

        private static IEnumerable<int> GetData()
        {
            return null;
        }
    }
}
Solution2: Using the 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>.

using System.Linq;
using System.Collections.Generic;
using System;
namespace LinqDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> integerSequence = GetData() ?? Enumerable.Empty<int>(); ;

            foreach (var num in integerSequence)
            {
                Console.WriteLine(num);
            }

            Console.ReadKey();
        }

        private static IEnumerable<int> GetData()
        {
            return null;
        }
    }
}

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 Reply

Your email address will not be published. Required fields are marked *