IsNullOrEmpty for Generic collections in C#

In this code snippet we will see creation and implementation of IsNullOrEmpty for collections.

Can I implement IsNullOrEmpty for my Generic collections/lists ?

Its out of C#. Unfortunately there is only one method which is of a String method String.IsNullOrEmpty() available, framework does not provide us such things.

What is the solution for this.
A solution is only Extension Method, we just need to create an Extension Method which will provide the same facility: Here is the extension method:

public static class CollectioncExtensionMethods  
    {  
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> genericEnumerable)  
        {  
            return ((genericEnumerable == null) || (!genericEnumerable.Any()));  
        }  
  
        public static bool IsNullOrEmpty<T>(this ICollection<T> genericCollection)  
        {  
            if (genericCollection == null)  
            {  
                return true;  
            }  
            return genericCollection.Count < 1;  
        }  
    }

Enjoy the benefit of these extension methods 🙂

var serverDataList = new List<ServerData>();  

//It will use IsNullOrEmpty<T>(this ICollection<T> gnericCollection)
var result = serverDataList.IsNullOrEmpty();  
 
var serverData = new ServerDataRepository().GetAll();
              
// It will use IsNullOrEmpty<T>(this IEnumerable<T> genericEnumerable)  
var result = serverData.IsNullOrEmpty();

Can you think what it will give when I call serverDataList.Count and when I call serverData.Count ?

Hint: One will give me O(n) while other O(1), enjoy 🙂

If still confused view this video on .Net collection by legend author Mr. Shivprasad Koirala

Leave A Reply