Stack.Clear Method in C#
Last Updated :
04 Feb, 2019
This method(comes under System.Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed. This method is an O(n) operation, where n is Count.
Syntax:
public virtual void Clear ();
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push( "1st Element" );
myStack.Push( "2nd Element" );
myStack.Push( "3rd Element" );
myStack.Push( "4th Element" );
myStack.Push( "5th Element" );
myStack.Push( "6th Element" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Clear();
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 6
Total number of elements in the Stack are : 0
Example 2:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push(3);
myStack.Push(5);
myStack.Push(7);
myStack.Push(9);
myStack.Push(11);
Console.Write( "Total number of elements " +
"in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Clear();
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 5
Total number of elements in the Stack are : 0
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...