03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

332 ❘ CHAPTER 14 Collection Classes<br />

You can also think of a stack as a stack of papers on a desk. You can add things on the top and take<br />

them off of the top, but you can’t pull papers out of the middle or the bottom of the stack without<br />

the whole thing toppling over.<br />

Normally, you use the Stack class’s Push and Pop methods to add and remove items from a stack,<br />

but the class also provides a few methods that let you cheat by peeking at the top item without<br />

removing it or by converting the Stack into an array.<br />

The following table describes the Stack class’s most useful properties and methods.<br />

Property/Method<br />

Clear<br />

Contains<br />

CopyTo<br />

Count<br />

Peek<br />

Pop<br />

Push<br />

ToArray<br />

Purpose<br />

Removes all the items.<br />

Returns true if the Stack contains a particular object.<br />

Copies some or all of the Stack’s objects into a onedimensional<br />

array.<br />

Returns the number of items in the Stack.<br />

Returns a reference to the Stack class’s top item without removing it<br />

from the Stack.<br />

Returns the Stack class’s top item and removes it from the Stack.<br />

Adds an item to the top of the Stack.<br />

Returns a one-dimensional array containing references to the objects<br />

in the Stack. The Stack class’s top item is placed first in the array.<br />

A Stack allocates memory to store its items. If you Push an object onto a Stack that is completely<br />

full, the Stack must resize itself to make more room and that slows things down.<br />

Like the Hashtable class, the Stack class provides overloaded constructors that let you determine<br />

how much memory should initially be allocated. The first constructor takes no parameters and<br />

allocates a default amount of memory.<br />

The second constructor takes as a parameter the number of items the Stack should initially hold.<br />

If you know that you will add 10,000 items to the Stack, you can avoid a lot of resizing by initially<br />

allocating room for 10,000 items.<br />

The third version of the constructor takes as a parameter an object that implements the ICollection<br />

interface. The constructor allocates enough room to hold the items in the ICollection and copies<br />

them into the Stack.<br />

The following short example demonstrates a Stack.<br />

Stack stack = new Stack();<br />

stack.Push("Apple");<br />

stack.Push("Banana");<br />

stack.Push("Cherry");<br />

Console.WriteLine(stack.Pop());<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!