Check whether a collection is null or empty - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Check whether a collection is null or empty

Demo Code

//    Copyright (c) CloudLibrary 2016.  All rights reserved.
using System.Collections.Generic;
using System.Collections;

public class Main{
        /// <summary>
        /// Check whether a collection is null or empty
        /// </summary>
        /// <param name="collection">collection to check</param>
        /// <returns>true if collection is either null or empty. False if collection is not null and contains item</returns>
        /// <remarks>
        /// String has a method called IsNullOrEmpty. We need similar method for collection because it is used wildly.
        /// </remarks>
        /// <example>
        /// Following is example of how to use it:
        /// <![CDATA[
        /// void Foo(ICollection dataToProcess)
        /// {/*  w  ww . jav a2s  . c  o m*/
        ///     if (dataToProcess.IsNullOrEmpty())
        ///     {
        ///         throw new ArgumentException("data should not be null or empty");
        ///     }
        ///     ...
        /// }
        /// ]]>
        /// </example>
        public static bool IsNullOrEmpty(this ICollection collection)
        {
            return (collection == null) || (collection.Count < 1);
        }
}

Related Tutorials