Click here to Skip to main content
15,884,629 members
Articles / Programming Languages / C#

IsNullOrEmpty for Generic Collections in C#

Rate me:
Please Sign up or sign in to vote.
3.43/5 (18 votes)
13 Aug 2015CPOL 33.6K   11  
IsNullOrEmpty for Generic Collections in C#
This is an old version of the currently published technical blog.

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

Can I implement IsNullOrEmpty for my Generic collections/lists?

It's 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:

C#
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. :)

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
India India
Learning never ends.

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.