Stack.Count Property in C#
Last Updated :
04 Feb, 2019
This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to Count. Retrieving the value of this property is an O(1) operation.
Syntax:
public virtual int Count { get; }
Return Value: It returns the number of elements contained in the Stack having type System.Int32.
Below programs illustrate the use of above-discussed property:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
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;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
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:
Share your thoughts in the comments
Please Login to comment...