In this code snippet, we will see the 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 an 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>();
var result = serverDataList.IsNullOrEmpty();
var serverData = new ServerDataRepository().GetAll();
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.