Handling Null/Empty situations while working with Generic Collections in C#


These days many of us are taking the advantages of Generic Collections, while working in C#. In this short article, we will discuss a problem of Null or Empty value.

Abstract


These days many of us are taking the advantages of Generic Collections, while working in C#.
In this short article, we will discuss a problem of Null or Empty value.

Problem


It breaks the code or throws the exception in case collection countered with null or empty value.
In C# there is no such way to handle this. However, we have one method, which is of a String method String.IsNullOrEmpty() and it only works for strings.

Solution


If we talk about the solution,so, what will be the best solution. Can we use string method to check Null or Empty values?

Lets think and find-out a proper solution. We can achive this by creating an extension method:

First create a class, named it as 'CollectioncExtensionMethods'

1. Create an extension method for IEnumerable:



public static bool IsNullOrEmpty(this IEnumerable genericEnumerable)
{
return ((genericEnumerable == null) || (!genericEnumerable.Any()));
}



2. Create an extension method for ICollection:

public static bool IsNullOrEmpty(this ICollection genericCollection)
{
if (genericCollection == null)
{
return true;
}
return genericCollection.Count < 1;
}


Now what?


We just need to use these extension methods and we are done! Isn't it easy :)

1. For collections:


var serverDataList = new List();
var result = serverDataList.IsNullOrEmpty();


2. For enumerable:


var serverData = new ServerDataRepository().GetAll();
var result = serverData.IsNullOrEmpty();


With the use of above, you need not to worry about Null or Empty things.

Closing Notes


In this short article, we discussed, how to handle the situation when our collection meet with 'Null' or 'Empty' siatuations. We overcome this
problem with the use of Extension Method.


Article by Gaurav Kumar Arora
Gaurav is a Microsoft Technology Specialist professional. He has awarded lifetime membership from Computer Society of India (CSI). He has more than 13yrs of experience in the industry. Currently, he is working in the capacity of Solution Architect with an MNC. He is serving to the various communities since 1999.

Follow Gaurav Kumar Arora or read 157 articles authored by Gaurav Kumar Arora

Comments

Author: Dotnet Developer-201514 Aug 2015 Member Level: Gold   Points : 0

Hi
Gaurav

Good post this one . How to Testing Realtime for this method . for ex: Button click event can you update this?

Author: Gaurav Kumar Arora01 Sep 2015 Member Level: Gold   Points : 0

Thanks, I will update source code with Unit testing



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: