Returns the element count of the collection. If collection is null or empty, returns zero - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Returns the element count of the collection. If collection is null or empty, returns zero

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;// w w w.j a  v  a 2 s  . c  om

public class Main{
        /// <summary>
        /// Returns the element count of the collection.
        /// If collection is null or empty, returns zero
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static int SafeCount<T>(this ICollection<T> source)
        {
            return source.IsNullOrEmpty() ? 0 : source.Count;
        }
        /// <summary>
        /// Determines if the collection is null or empty.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <returns>
        ///   <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsNullOrEmpty<T>(this ICollection<T> source)
        {
            return source == null || source.Count == 0;
        }
}

Related Tutorials