Removing the object from the top of the Stack in C#
Last Updated :
28 Jan, 2019
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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
Stack< string > myStack = new Stack< string >();
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);
Console.Write( "Top element of Stack is: " );
Console.Write(myStack.Pop());
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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
Stack< int > myStack = new Stack< int >();
myStack.Push(7);
myStack.Push(9);
Console.WriteLine( "Number of elements in the Stack: {0}" ,
myStack.Count);
Console.Write( "Top element of Stack is: " );
Console.Write(myStack.Pop());
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...