How to check if a Stack<T> is empty

Instead of using .Count() == 0, just use .Count == 0. This is using the stack's property rather than the linq extension method.


There are three common approaches, and which one you use will usually be a matter of taste.

if(!stack.Any()) ...
if(stack.Count() == 0) ...
if(stack.Count == 0) ...

Profiling the different approaches looks like this:

Benchmark

.Any() and .Count() take 10x-20x longer than .Count... and can still run tens of thousands of times per millisecond. So .Count > 0 is "much faster", but the others are still fast enough to not have to worry about under most circumstances. I'd personally stick with Any() since I feel it reads better, but I wouldn't give anyone flak for choosing Count.


You can create your own extension method too

namespace System.Collection.Generic {
   public static class SystemEx {
        public static bool IsEmpty<T>(this Stack<T> stack) {
            return (stack.Count==0);
        }    
   }

Tags:

C#

Stack

Is Empty