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?

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221
  • possible duplicate of [How to check if IEnumerable is null or empty?](http://stackoverflow.com/questions/5047349/how-to-check-if-ienumerable-is-null-or-empty) – octothorpentine Jul 23 '15 at 21:40

3 Answers3

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;
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • +1, but note that `ICollection` does not inherit from `ICollection`, so you might want to make two extension methods, one for each interface. – phoog Aug 03 '12 at 05:06
  • why not use Any instead of Count so that we can avoid iterating the whole list? – Louis Rhys Aug 05 '12 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 06 '12 at 02: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()](http://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0) – Habib Aug 06 '12 at 03: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.

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

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

STiLeTT
  • 1,023
  • 10
  • 23