Stack Class
Represents a simple last-in-first-out (LIFO) non-generic collection of objects.

Namespace: System.Collections
Assembly: mscorlib (in mscorlib.dll)

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class Stack
    Implements ICollection, IEnumerable, ICloneable
Visual Basic (Usage)
Dim instance As Stack
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class Stack : ICollection, IEnumerable, ICloneable
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class Stack : ICollection, IEnumerable, ICloneable
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class Stack implements ICollection, IEnumerable, 
    ICloneable
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public class Stack implements ICollection, IEnumerable, 
    ICloneable
XAML
Not applicable.
Remarks

For the generic version of this collection, see System.Collections.Generic.Stack.

Stack is implemented as a circular buffer.

The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.

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. Pop is an O(1) operation.

Stack accepts a null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements.

Example

The following example shows how to create and add values to a Stack and how to print out its values.

Visual Basic
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesStack    
    
    Public Shared Sub Main()
    
        ' Creates and initializes a new Stack.
        Dim myStack As New Stack()
        myStack.Push("Hello")
        myStack.Push("World")
        myStack.Push("!")
        
        ' Displays the properties and values of the Stack.
        Console.WriteLine("myStack")
        Console.WriteLine(ControlChars.Tab & "Count:    {0}", myStack.Count)
        Console.Write(ControlChars.Tab & "Values:")
        PrintValues(myStack)
    End Sub
    
    Public Shared Sub PrintValues(myCollection As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myCollection
            Console.Write("    {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub 'PrintValues

End Class

' This code produces the following output.
'
' myStack
'     Count:     3
'     Values:    !    World    Hello
C#
using System;
using System.Collections;
public class SamplesStack  {

   public static void Main()  {

      // Creates and initializes a new Stack.
      Stack myStack = new Stack();
      myStack.Push("Hello");
      myStack.Push("World");
      myStack.Push("!");

      // Displays the properties and values of the Stack.
      Console.WriteLine( "myStack" );
      Console.WriteLine( "\tCount:    {0}", myStack.Count );
      Console.Write( "\tValues:" );
      PrintValues( myStack );
   }

   public static void PrintValues( IEnumerable myCollection )  {
      foreach ( Object obj in myCollection )
         Console.Write( "    {0}", obj );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

myStack
    Count:    3
    Values:    !    World    Hello
*/ 
C++
using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myCollection );
int main()
{
   
   // Creates and initializes a new Stack.
   Stack^ myStack = gcnew Stack;
   myStack->Push( "Hello" );
   myStack->Push( "World" );
   myStack->Push( "!" );
   
   // Displays the properties and values of the Stack.
   Console::WriteLine( "myStack" );
   Console::WriteLine( "\tCount:    {0}", myStack->Count );
   Console::Write( "\tValues:" );
   PrintValues( myStack );
}

void PrintValues( IEnumerable^ myCollection )
{
   IEnumerator^ myEnum = myCollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "    {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 myStack
     Count:    3
     Values:    !    World    Hello
 */
J#
import System.*;
import System.Collections.*;

public class SamplesStack
{
    public static void main(String[] args)
    {
        // Creates and initializes a new Stack.
        Stack myStack = new Stack();

        myStack.Push("Hello");
        myStack.Push("World");
        myStack.Push("!");

        // Displays the properties and values of the Stack.
        Console.WriteLine("myStack");
        Console.WriteLine("\tCount:    {0}", 
            System.Convert.ToString(myStack.get_Count()));
        Console.Write("\tValues:");
        PrintValues(myStack);
    } //main

    public static void PrintValues(IEnumerable myCollection)
    {
        IEnumerator objEnum = myCollection.GetEnumerator();

        while (objEnum.MoveNext()) {
            Console.Write("    {0}", objEnum.get_Current());
        }
        Console.WriteLine();
    } //PrintValues

} //SamplesStack

/* 
 This code produces the following output.
 
 myStack
     Count:    3
     Values:    !    World    Hello
 */
Inheritance Hierarchy

System.Object
  System.Collections.Stack
     Microsoft.VisualC.SymbolTableStack
Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Platforms

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

Version Information

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
See Also

Tags :


Community Content

David M. Kean - MSFT
Look at Stack<T> class instead
If you are targeting the .NET Framework 2.0 or higher, have a look at the generic Stack<T> class. Unlike Stack, it is strongly typed and prevents boxing for value types (structures).
Tags :

Page view tracker