Program defensively and use option 1.
Stack class provides the ability to check whether it contains anything before trying to
Pop a value from it, you should do the check and avoid using the exception for flow control.
If you want to avoid doing the
if check throughout your application, you could create a
public static class StackExtensions
public static bool TryPop<T>(this Stack<T> stack, out T value)
if (stack.Count > 0)
value = stack.Pop();
value = default(T);
It could be used in the following way:
if (availableResources.TryPop(out resource))
// use `resource` for something
It's worth noting that this approach is only suitable if the
Stack is not accessed concurrently! - If it is, and you are using .NET 4.0 onwards then you should use ConcurrentStack, otherwise create your own concurrent stack which encapsulates a
Stack and manages access to it with locks.