System.Collections.Stack Class

Assembly: Mscorlib.dll
Namespace: System.Collections
Summary
Represents a simple last-in-first-out collection of objects.
C# Syntax:
[Serializable]
public class Stack : ICollection, IEnumerable, ICloneable
Thread Safety
Public static (non-instance) members of this type are safe for multithreaded operations. 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 Stack.Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

Remarks
Stack is implemented as a circular buffer.

If Stack.Count is less than the capacity of the stack, Stack.Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Stack.Push becomes an O(n) operation, where n is Stack.Count. Stack.Pop is an O(1) operation.

Example
The following example shows how to create and add values to a Stack and how to print out its values.
 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 )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "\t{0}", myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myStack
     Count:    3
     Values:    !    World    Hello
 */ 

    
See also:
System.Collections Namespace

System.Collections.Stack Member List:

Public Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the Stack class that is empty and has the default initial capacity.
ctor #2 Overloaded:
.ctor(ICollection col)

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.
ctor #3 Overloaded:
.ctor(int initialCapacity)

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.
Public Properties
Count Read-only

Gets the number of elements contained in the Stack.
IsSynchronized Read-only

Gets a value indicating whether access to the Stack is synchronized (thread-safe).
SyncRoot Read-only

Gets an object that can be used to synchronize access to the Stack.
Public Methods
Clear Removes all objects from the Stack.
Clone Creates a shallow copy of the Stack.
Contains Determines whether an element is in the Stack.
CopyTo Copies the Stack to an existing one-dimensional Array, starting at the specified array index.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetEnumerator Returns an IEnumerator for the Stack.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
Peek Returns the object at the top of the Stack without removing it.
Pop Removes and returns the object at the top of the Stack.
Push Inserts an object at the top of the Stack.
Synchronized Returns a synchronized (thread-safe) wrapper for the Stack.
ToArray Copies the Stack to a new array.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Collections.Stack Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the Stack class that is empty and has the default initial capacity.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public Stack();
Remarks
The initial capacity is the starting capacity of the new Stack. The default initial capacity for a Stack is 10.

If the number of elements added to the stack reaches the current capacity, the capacity is automatically doubled.

Return to top


Overloaded ctor #2
Summary
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.
C# Syntax:
public Stack(
   ICollection col
);
Parameters:

col

The ICollection to copy elements from.

Exceptions
Exception Type Condition
ArgumentNullException col is null.
Remarks
The initial capacity is the starting capacity of the new Stack. If the number of elements added to the stack reaches the current capacity, the capacity is automatically doubled.

The elements are copied onto the Stack in the same order they are read by the IEnumerator of the ICollection.

See also:
ICollection | IEnumerator

Return to top


Overloaded ctor #3
Summary
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.
C# Syntax:
public Stack(
   int initialCapacity
);
Parameters:

initialCapacity

The initial number of elements that the Stack can contain.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException initialCapacity is less than zero.
Remarks
The initial capacity is the starting capacity of the new Stack. The default initial capacity for a Stack is 10.

If the number of elements added to the stack reaches the current capacity, the capacity is automatically doubled. Therefore, if the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Stack.

Return to top


Property: Count (read-only)
Summary
Gets the number of elements contained in the Stack.
C# Syntax:
public virtual int Count {get;}
Implements:
ICollection.Count

Return to top


Property: IsSynchronized (read-only)
Summary
Gets a value indicating whether access to the Stack is synchronized (thread-safe).
C# Syntax:
public virtual bool IsSynchronized {get;}
Implements:
ICollection.IsSynchronized
Remarks
To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Stack.Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

The following code example shows how to lock the collection using the Stack.SyncRoot during the entire enumeration:

              Stack myCollection = new Stack();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Stack, determine if a Stack is synchronized and use a synchronized Stack.
using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
 
       // Creates a synchronized wrapper around the Stack.
       Stack mySyncdStack = Stack.Synchronized( myStack );
 
       // Displays the sychronization status of both Stacks.
       Console.WriteLine( "myStack is {0}.",
          myStack.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdStack is {0}.",
          mySyncdStack.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myStack is not synchronized.
 mySyncdStack is synchronized.
 */ 

    

Return to top


Property: SyncRoot (read-only)
Summary
Gets an object that can be used to synchronize access to the Stack.
C# Syntax:
public virtual object SyncRoot {get;}
Implements:
ICollection.SyncRoot
Remarks
To create a synchronized version of the Stack, use the Stack.Synchronized method. However, derived classes can provide their own synchronized version of the Stack using the Stack.SyncRoot property. The synchronizing code must perform operations on the Stack.SyncRoot of the Stack, not directly on the Stack. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the Stack object.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

The following code example shows how to lock the collection using the Stack.SyncRoot during the entire enumeration:

              Stack myCollection = new Stack();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            

Return to top


Method: Clear()
Summary
Removes all objects from the Stack.
C# Syntax:
public virtual void Clear();
Remarks
Stack.Count is set to zero.
Example
The following example shows how to clear the values of the Stack.
 using System;
 using System.Collections;
 
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
       myStack.Push( "jumped" );
 
       // Displays the count and values of the Stack.
       Console.WriteLine( "Initially," );
       Console.WriteLine( "   Count    : {0}", myStack.Count );
       Console.Write( "   Values:" );
       PrintValues( myStack );
 
       // Clears the Stack.
       myStack.Clear();
 
       // Displays the count and values of the Stack.
       Console.WriteLine( "After Clear," );
       Console.WriteLine( "   Count    : {0}", myStack.Count );
       Console.Write( "   Values:" );
       PrintValues( myStack );
    }
 
 
    public static void PrintValues( IEnumerable myCollection )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "\t{0}", myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initially,
    Count    : 5
    Values:    jumped    fox    brown    quick    The
 After Clear,
    Count    : 0
    Values:
 */ 

    

Return to top


Method: Clone()
Summary
Creates a shallow copy of the Stack.
C# Syntax:
public virtual object Clone();
Return Value:
A shallow copy of the Stack.
Implements:
ICloneable.Clone
Remarks
A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.

In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements.

Return to top


Method: Contains(
   object obj
)
Summary
Determines whether an element is in the Stack.
C# Syntax:
public virtual bool Contains(
   object obj
);
Parameters:

obj

The Object to locate in the Stack. The element to locate can be null. The Object to locate in the Stack. The element to locate can be null.

Return Value:
true if obj is found in the Stack; otherwise, false.
Remarks
This method performs a linear search; therefore, the average execution time is proportional to Stack.Count. That is, this method is an O(n) operation, where n is Stack.Count.

This method determines equality by calling Object.Equals.

Return to top


Method: CopyTo(
   Array array,
   int index
)
Summary
Copies the Stack to an existing one-dimensional Array, starting at the specified array index.
C# Syntax:
public virtual void CopyTo(
   Array array,
   int index
);
Parameters:

array

The one-dimensional Array that is the destination of the elements copied from Stack. The Array must have zero-based indexing.

index

The zero-based index in array at which copying begins.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException index is less than zero.
ArgumentException array is multidimensional.

-or-

index is equal to or greater than the length of array.

-or-

The number of elements in the source Stack is greater than the available space from index to the end of the destination array.

InvalidCastException The type of the source Stack cannot be cast automatically to the type of the destination array.
Implements:
ICollection.CopyTo
Remarks
The elements are copied onto the array in a last-in-first-out order, similar to the order of the elements returned by a succession of calls to Stack.Pop.
Example
The following example shows how to copy a Stack into a one-dimensional Array instance and into a one-dimensional standard array.
 using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes the source Stack.
       Stack mySourceQ = new Stack();
       mySourceQ.Push( "barn" );
       mySourceQ.Push( "the" );
       mySourceQ.Push( "in" );
       mySourceQ.Push( "cats" );
       mySourceQ.Push( "napping" );
       mySourceQ.Push( "three" );
 
       // Creates and initializes the one-dimensional target Array.
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Array contains the following (before and after copying):" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Stack to the target Array, starting at index 6.
       mySourceQ.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Stack to a new standard array.
       Object[] myStandardArray = mySourceQ.ToArray();
 
       // Displays the values of the new standard array.
       Console.WriteLine( "The new standard array contains the following:" );
       PrintValues( myStandardArray, ' ' );
 
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 
    public static void PrintValues( Object[] myArr, char mySeparator )  {
       foreach ( Object myObj in myArr )  {
          Console.Write( "{0}{1}", mySeparator, myObj );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Array contains the following (before and after copying):
  The quick brown fox jumped over the lazy dog      
  The quick brown fox jumped over three napping cats in the barn   
 The new standard array contains the following:
  three napping cats in the barn
 */ 

    
See also:
Stack.ToArray

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Stack();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Returns an IEnumerator for the Stack.
C# Syntax:
public virtual IEnumerator GetEnumerator();
Return Value:
An IEnumerator for the Stack.
Implements:
IEnumerable.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current will return the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

See also:
IEnumerator

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Peek()
Summary
Returns the object at the top of the Stack without removing it.
C# Syntax:
public virtual object Peek();
Return Value:
The Object at the top of the Stack.
Exceptions
Exception Type Condition
InvalidOperationException The Stack is empty.
Remarks
null can be pushed onto the Stack as a placeholder, if needed. To distinguish between a null value and the end of the stack, check the Stack.Count property or catch the InvalidOperationException, which is thrown when the Stack is empty.
Example
The following example shows how to add elements to the Stack, remove elements from the Stack or just view the element at the top of the Stack.
 using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes an element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes another element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Views the first element in the Stack but does not remove it.
       Console.WriteLine( "(Peek)\t\t{0}", myStack.Peek() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Stack values:    fox    brown    quick    The
 (Pop)        fox
 Stack values:    brown    quick    The
 (Pop)        brown
 Stack values:    quick    The
 (Peek)        quick
 Stack values:    quick    The
 */ 

    
See also:
Stack.Pop | Stack.Push

Return to top


Method: Pop()
Summary
Removes and returns the object at the top of the Stack.
C# Syntax:
public virtual object Pop();
Return Value:
The Object removed from the top of the Stack.
Exceptions
Exception Type Condition
InvalidOperationException The Stack is empty.
Remarks
Stack is implemented as a circular buffer. Stack.Pop is an O(1) operation.

null can be pushed onto the Stack as a placeholder, if needed. To distinguish between a null value and the end of the stack, check the Stack.Count property or catch the InvalidOperationException, which is thrown when the Stack is empty.

Example
The following example shows how to add elements to the Stack, remove elements from the Stack or just view the element at the top of the Stack.
 using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes an element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes another element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Views the first element in the Stack but does not remove it.
       Console.WriteLine( "(Peek)\t\t{0}", myStack.Peek() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Stack values:    fox    brown    quick    The
 (Pop)        fox
 Stack values:    brown    quick    The
 (Pop)        brown
 Stack values:    quick    The
 (Peek)        quick
 Stack values:    quick    The
 */ 

    
See also:
Stack.Peek | Stack.Push

Return to top


Method: Push(
   object obj
)
Summary
Inserts an object at the top of the Stack.
C# Syntax:
public virtual void Push(
   object obj
);
Parameters:

obj

The Object to push onto the Stack.

Remarks
Stack is implemented as a circular buffer.

If Stack.Count is less than the capacity of the stack, Stack.Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Stack.Push becomes an O(n) operation, where n is Stack.Count.

null can be pushed onto the Stack as a placeholder, if needed. It occupies a slot in the stack and is treated like any object.

Example
The following example shows how to add elements to the Stack, remove elements from the Stack or just view the element at the top of the Stack.
 using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes an element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Removes another element from the Stack.
       Console.WriteLine( "(Pop)\t\t{0}", myStack.Pop() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
 
       // Views the first element in the Stack but does not remove it.
       Console.WriteLine( "(Peek)\t\t{0}", myStack.Peek() );
 
       // Displays the Stack.
       Console.Write( "Stack values:" );
       PrintValues( myStack, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Stack values:    fox    brown    quick    The
 (Pop)        fox
 Stack values:    brown    quick    The
 (Pop)        brown
 Stack values:    quick    The
 (Peek)        quick
 Stack values:    quick    The
 */ 

    
See also:
Stack.Peek | Stack.Pop

Return to top


Method: Synchronized(
   Stack stack
)
Summary
Returns a synchronized (thread-safe) wrapper for the Stack.
C# Syntax:
public static Stack Synchronized(
   Stack stack
);
Parameters:

stack

The Stack to synchronize.

Return Value:
A synchronized wrapper around the Stack.
Exceptions
Exception Type Condition
ArgumentNullException stack is null.
Remarks
To guarantee the thread safety of the Stack, all operations must be done through this wrapper.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could 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.

The following code example shows how to lock the collection using the Stack.SyncRoot during the entire enumeration:

              Stack myCollection = new Stack();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Stack, determine if a Stack is synchronized and use a synchronized Stack.
using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes a new Stack.
       Stack myStack = new Stack();
       myStack.Push( "The" );
       myStack.Push( "quick" );
       myStack.Push( "brown" );
       myStack.Push( "fox" );
 
       // Creates a synchronized wrapper around the Stack.
       Stack mySyncdStack = Stack.Synchronized( myStack );
 
       // Displays the sychronization status of both Stacks.
       Console.WriteLine( "myStack is {0}.",
          myStack.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdStack is {0}.",
          mySyncdStack.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myStack is not synchronized.
 mySyncdStack is synchronized.
 */ 

    

Return to top


Method: ToArray()
Summary
Copies the Stack to a new array.
C# Syntax:
public virtual object[] ToArray();
Return Value:
A new array containing copies of the elements of the Stack.
Remarks
The elements are copied onto the array in a last-in-first-out order, similar to the order of the elements returned by a succession of calls to Stack.Pop.
Example
The following example shows how to copy a Stack into a one-dimensional Array instance and into a one-dimensional standard array.
 using System;
 using System.Collections;
 public class SamplesStack  {
 
    public static void Main()  {
 
       // Creates and initializes the source Stack.
       Stack mySourceQ = new Stack();
       mySourceQ.Push( "barn" );
       mySourceQ.Push( "the" );
       mySourceQ.Push( "in" );
       mySourceQ.Push( "cats" );
       mySourceQ.Push( "napping" );
       mySourceQ.Push( "three" );
 
       // Creates and initializes the one-dimensional target Array.
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Array contains the following (before and after copying):" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Stack to the target Array, starting at index 6.
       mySourceQ.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Stack to a new standard array.
       Object[] myStandardArray = mySourceQ.ToArray();
 
       // Displays the values of the new standard array.
       Console.WriteLine( "The new standard array contains the following:" );
       PrintValues( myStandardArray, ' ' );
 
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 
    public static void PrintValues( Object[] myArr, char mySeparator )  {
       foreach ( Object myObj in myArr )  {
          Console.Write( "{0}{1}", mySeparator, myObj );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Array contains the following (before and after copying):
  The quick brown fox jumped over the lazy dog      
  The quick brown fox jumped over three napping cats in the barn   
 The new standard array contains the following:
  three napping cats in the barn
 */ 

    
See also:
Stack.CopyTo | Stack.Pop

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.