0

String has a convenient String.IsNullOrEmpty method for checking whether a string is null or has zero length. Is there something similar in out-of-the-box .net?

1

3 Answers 3

17

There is not, but I think you can write your own extension method for that.

public static bool IsNullOrEmpty(this ICollection collection)
{
    if (collection == null)
        return true;

    return  collection.Count < 1;
}
4
  • +1, but note that ICollection<T> does not inherit from ICollection, so you might want to make two extension methods, one for each interface.
    – phoog
    Aug 3, 2012 at 5:06
  • why not use Any instead of Count so that we can avoid iterating the whole list?
    – Louis Rhys
    Aug 5, 2012 at 22:26
  • 1
    @LouisRhys Did you notice the Count is missing the brackets? This is not the Count() extension method, it is the Count property so it will not enumerate the entire list.
    – MikeKulls
    Aug 6, 2012 at 2:06
  • @LouisRhys, ICollection doesn't have Any Extension method, also the above code is using Count property. You may wanna see this thread: Count Vs Any()
    – Habib
    Aug 6, 2012 at 3:15
8

This is a more generic extension method that will work on any IEnumerable.

    public static bool IsNullOrEmpty(this IEnumerable collection)
    {
        return collection == null || !collection.Cast<object>().Any();
    }

I'm not a big fan of functions that return true if something is empty, I always find most of the time I need to add a ! to the front of string.IsNullOrEmptyString. I would write it as "ExistsAndHasItems" or something like that.

2
  • 2
    why do you have Cast<object>? Why not just make the signature IEnumerable<T>?
    – Louis Rhys
    Aug 5, 2012 at 22:25
  • @LouisRhys That is a good question. The idea was to make it as generic as possible. Since IEnumerable<T> inherits from IEnumerable, making it IEnumerable will allow it to work for IEnumerable<T> anyway so allow it to work with the greatest number of collections.
    – MikeKulls
    Aug 6, 2012 at 2:05
1

No, there isn't any, but you can create an extension method yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.