If you don't need it anymore and it implements IDisposable
use the using
-statement.
public void EndOperation()
{
// Pop object from stack.
if (stack.Count != 0)
{
using(var context = stack.Pop())
{
// ... do various stuff with 'context' ...
}
}
}
Apart from that Stack.Pop
is implemented in this way(ILSPy, .NET 4):
// System.Collections.Stack
public virtual object Pop()
{
if (this._size == 0)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
}
this._version++;
object result = this._array[--this._size];
this._array[this._size] = null;
return result;
}
So you see that there's no reference anymore in the stack after Pop
.
In general you should use using
(or try-finally
) whenever you use unmanaged resources. On this way it is ensured that they are disposed even on error.