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
{
return ((genericEnumerable == null) || (!genericEnumerable.Any()));
}
2. Create an extension method for ICollection:
public static bool IsNullOrEmpty
{
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.
Hi
Gaurav
Good post this one . How to Testing Realtime for this method . for ex: Button click event can you update this?