This method(comes under System.Collections namespace) is used to inserts an object at the top of the Stack. If the Count already equals the capacity, the capacity of the Stack is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count.
Syntax:
public virtual void Push (object obj);
Example:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push( "one" );
Console.Write( "Total number of elements " +
"in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "two" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "three" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "four" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "five" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "six" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 1
Total number of elements in the Stack are : 2
Total number of elements in the Stack are : 3
Total number of elements in the Stack are : 4
Total number of elements in the Stack are : 5
Total number of elements in the Stack are : 6
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
04 Feb, 2019
Like Article
Save Article