Search code examples
c#collectionsstack

C# Stack Modify Top Element


If I want to modify the top of the Stack, how would I do that?

I know you can use Stack.Pop() and then push back the modified value, but that seems inelegant. Is there another way?

Example:

Stack<string> stringStack;
stringStack.Push("foo");
stringStack.Push("ba");
stringStack.Replace("bar"); //implementation 

This seems it has a really obvious answer to it. Don't know why it's not implemented yet.


Solution

  • You can create an extension method like this;

    public static class StackExtensions
    {
        public static void Replace<T>(this Stack<T> stack, T item)
        {
            stack.Pop();
            
            stack.Push(item);
        }
    }
    

    And you can use it like this;

    var stringStack = new Stack<string>();
    stringStack.Push("foo");
    stringStack.Push("ba");
    stringStack.Replace("bar");
    
    foreach (var item in stringStack)
    {
        Console.WriteLine(item);
    }
    

    Which will give you this output;

    bar
    foo