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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
Stack< string > myStack = new Stack< string >();
myStack.Push( "Chandigarh" );
myStack.Push( "Delhi" );
myStack.Push( "Noida" );
myStack.Push( "Himachal" );
myStack.Push( "Punjab" );
myStack.Push( "Jammu" );
Console.Write( "Total number of elements in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 6
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
Stack< int > myStack = new Stack< int >();
Console.Write( "Total number of elements in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 0
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...