This documentation is archived and is not being maintained.

Stack.Peek Method

Returns the object at the top of the Stack without removing it.

Namespace: System.Collections.Generic
Assembly: System (in system.dll)

public:
T Peek ()
public T Peek ()
public function Peek () : T
Not applicable.

Return Value

The object at the top of the Stack.

Exception typeCondition

InvalidOperationException

The Stack is empty.

This method is similar to the Pop method, but Peek does not modify the Stack.

If type T is a reference type, a null reference (Nothing in Visual Basic) can be pushed onto the Stack as a placeholder, if needed.

This method is an O(1) operation.

The following code example demonstrates several methods of the Stack generic class, including the Peek method.

The code example creates a stack of strings with default capacity and uses the Push method to push five strings onto the stack. The elements of the stack are enumerated, which does not change the state of the stack. The Pop method is used to pop the first string off the stack. The Peek method is used to look at the next item on the stack, and then the Pop method is used to pop it off.

The ToArray method is used to create an array and copy the stack elements to it, then the array is passed to the Stack constructor that takes IEnumerable, creating a copy of the stack with the order of the elements reversed. The elements of the copy are displayed.

An array twice the size of the stack is created, and the CopyTo method is used to copy the array elements beginning at the middle of the array. The Stack constructor is used again to create a copy of the stack with the order of elements reversed; thus, the three null elements are at the end.

The Contains method is used to show that the string "four" is in the first copy of the stack, after which the Clear method clears the copy and the Count property shows that the stack is empty.

No code example is currently available or this language may not be supported.

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.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0
Show: