Open In App

Stack.Pop() Method in C#

Improve
Improve
Like Article
Like
Save
Share
Report

This method(comes under System.Collections namespace) is used to remove and returns the object at the top of the Stack. This method is similar to the Peek method, but Peek does not modify the Stack.

Syntax:

public virtual object Pop ();

Return Value: It returns the Object removed from the top of the Stack.

Exception : This method will give InvalidOperationException if the Stack is empty.

Below programs illustrate the use of the above-discussed method:

Example 1:




// C# Program to illustrate the 
// use of Stack.Pop() Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                 myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}


Output:

Number of elements in the Stack: 5
Top element of Stack is: GeeksforGeeks
Number of elements in the Stack: 4

Example 2:




// C# Program to illustrate the 
// use of Stack.Pop() Method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(7);
        myStack.Push(9);
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                 myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}


Output:

Number of elements in the Stack: 2
Top element of Stack is: 9
Number of elements in the Stack: 1

Reference:



Last Updated : 04 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads