C# | Get the number of elements contained in the Stack

Stack represents a last-in, first out collection of object.
Stack<T>.Count Property is used to gets the number of elements contained in the Stack. Retrieving the value of this property is an O(1) operation.

Syntax:

myStack.Count 

Here myStack is the name of the Stack<T>



Return Value: The property returns the number of elements contained in the Stack<T>.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to Get the number of
// elements contained in the Stack
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack of strings
        Stack<string> myStack = new Stack<string>();
  
        // Inserting the elements into the Stack
        myStack.Push("Chandigarh");
        myStack.Push("Delhi");
        myStack.Push("Noida");
        myStack.Push("Himachal");
        myStack.Push("Punjab");
        myStack.Push("Jammu");
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
    }
}

chevron_right


Output:

Total number of elements in the Stack are : 6

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to Get the number of
// elements contained in the Stack
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack of Integers
        Stack<int> myStack = new Stack<int>();
  
        // Displaying the count of elements
        // contained in the Stack
        Console.Write("Total number of elements in the Stack are : ");
  
        // The function should return 0
        // as the Stack is empty and it
        // doesn't contain any element
        Console.WriteLine(myStack.Count);
    }
}

chevron_right


Output:

Total number of elements in the Stack are : 0

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.