Removing the object from the top of the Stack in C#
Stack<T>.Pop Method is used to remove and returns the object at the top of the Stack<T>. This method comes under the System.Collections.Generic namespace.
Syntax:
public T Pop ();
Return Value: It returns the Object which is to be removed from the top of the Stack.
Exception : This method will give InvalidOperationException if the Stack<T> is empty.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# Program to illustrate the // use of Stack<T>.Pop() Method using System; using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of Strings Stack< string > myStack = new Stack< string >(); // Inserting the elements into the Stack myStack.Push( "Beginner" ); myStack.Push( "Beginner Classes" ); myStack.Push( "Noida" ); myStack.Push( "Data Structures" ); myStack.Push( "w3wiki" ); 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: w3wiki Number of elements in the Stack: 4
Example 2:
// C# Program to illustrate the // use of Stack<T>.Pop() Method using System; using System.Collections.Generic; class GFG { // Main Method public static void Main() { // Creating a Stack of integers Stack< int > myStack = new Stack< int >(); // 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:
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.pop?view=netframework-4.7.2
Contact Us