In my previous interview I have got one bumbarded question.
Q. Can I implement IsNullOrEmpty for my Generic collections/lists ?
Ans. 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>();
var result = serverDataList.IsNullOrEmpty();//It will use IsNullOrEmpty<T>(this ICollection<T> gnericCollection) 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 :)
