Open In App

Stack.Push() Method in C#

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:




// C# code to demonstrate the 
// Stack.Push() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("one");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements "+
                           "in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("two");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("three");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("four");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("five");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
  
        Console.WriteLine(myStack.Count);
  
        myStack.Push("six");
  
        // Displaying the count of elements
        // contained in the Stack
        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:



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