Skip to main content
.NET Framework Class Library
Stack Class

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

Inheritance Hierarchy
System..::.Object
  System.Collections..::.Stack

Namespace: System.Collections
Assembly: mscorlib (in mscorlib.dll)
Syntax
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class Stack _
	Implements ICollection, IEnumerable, ICloneable
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Stack : ICollection, IEnumerable, 
	ICloneable
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Stack : ICollection, IEnumerable, 
	ICloneable
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type Stack =  
    class
        interface ICollection
        interface IEnumerable
        interface ICloneable
    end

The Stack type exposes the following members.

Constructors
 NameDescription
Public methodSupported by the XNA FrameworkStack()()()Initializes a new instance of the Stack class that is empty and has the default initial capacity.
Public methodSupported by the XNA FrameworkStack(ICollection)Initializes a new instance of the Stack class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied.
Public methodSupported by the XNA FrameworkStack(Int32)Initializes a new instance of the Stack class that is empty and has the specified initial capacity or the default initial capacity, whichever is greater.
Top
Properties
 NameDescription
Public propertySupported by the XNA FrameworkCountGets the number of elements contained in the Stack.
Public propertySupported by the XNA FrameworkIsSynchronizedGets a value indicating whether access to the Stack is synchronized (thread safe).
Public propertySupported by the XNA FrameworkSyncRootGets an object that can be used to synchronize access to the Stack.
Top
Methods
 NameDescription
Public methodSupported by the XNA FrameworkClearRemoves all objects from the Stack.
Public methodSupported by the XNA FrameworkCloneCreates a shallow copy of the Stack.
Public methodSupported by the XNA FrameworkContainsDetermines whether an element is in the Stack.
Public methodSupported by the XNA FrameworkCopyToCopies the Stack to an existing one-dimensional Array, starting at the specified array index.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetEnumeratorReturns an IEnumerator for the Stack.
Public methodSupported by the XNA FrameworkGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkPeekReturns the object at the top of the Stack without removing it.
Public methodSupported by the XNA FrameworkPopRemoves and returns the object at the top of the Stack.
Public methodSupported by the XNA FrameworkPushInserts an object at the top of the Stack.
Public methodStatic memberSupported by the XNA FrameworkSynchronizedReturns a synchronized (thread safe) wrapper for the Stack.
Public methodSupported by the XNA FrameworkToArrayCopies the Stack to a new array.
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Extension Methods
 NameDescription
Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodSupported by the XNA FrameworkCast<(Of <(TResult>)>)Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodSupported by the XNA FrameworkOfType<(Of <(TResult>)>)Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top
Remarks

For the generic version of this collection, see System.Collections.Generic..::.Stack<(Of <(T>)>).

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 nullNothingnullptra null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements.

Examples

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


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


 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
 */ 



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
 */

Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
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.