Stacks

A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table, or a stack of coins on your desk. Add a dish on top, which is the first dish you take off the stack.

The principal methods for adding to and removing from a stack are Push and Pop( ) ; Stack also offers a Peek( ) method, very much like Queue. The significant methods and properties for Stack are shown in Table 9-5.

Table 9-5. Stack methods and properties

Method or property

Purpose

Synchronized( )

Public static method that returns a thread-safe Stack wrapper.

Count

Public property that gets the number of elements in the Stack.

IsSynchronized

Public property that gets a value indicating if the Stack is synchronized.

SyncRoot

Public property that returns an object that can be used to synchronize access to the Stack.

Clear( )

Removes all objects from the Stack.

Clone( )

Creates a shallow copy.

Contains( )

Determines if an element is in the Stack.

CopyTo( )

Copies the Stack elements to an existing one-dimensional array.

GetEnumerator( )

Returns an enumerator for the Stack.

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.

ToArray( )

Copies the elements to a new array.

The ArrayList, Queue, and Stack types contain overloaded CopyTo( ) and ToArray( ) methods for copying their elements to an array. In the ...

Get Programming C#, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.