15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

240 ❘ ChaPTer 10 cOllectiOns<br />

When you start the application, the documents are added to <strong>and</strong> removed from the queue, <strong>and</strong> you get<br />

output similar to the following:<br />

Added document Doc 279<br />

Processing document Doc 236<br />

Added document Doc 280<br />

Processing document Doc 237<br />

Added document Doc 281<br />

Processing document Doc 238<br />

Processing document Doc 239<br />

Processing document Doc 240<br />

Processing document Doc 241<br />

Added document Doc 282<br />

Processing document Doc 242<br />

Added document Doc 283<br />

Processing document Doc 243<br />

A real-life scenario doing the task described with the sample application can<br />

be an application that processes documents received with a Web service.<br />

Push<br />

Pop<br />

ckaCK<br />

A stack is another container that is very similar to the queue. You just use<br />

different methods to access the stack. The item that is added last to the stack<br />

is read first. The stack is a last in, first out (LIFO) container.<br />

Figure 10-2 shows the representation of a stack where the Push() method<br />

adds an item to the stack, <strong>and</strong> the Pop() method gets the item that was<br />

added last.<br />

Similar to the Queue class, the Stack class implements the interfaces<br />

IEnumerable <strong>and</strong> ICollection.<br />

Members of the Stack class are listed in the following table.<br />

figure 10-2<br />

seleCTed sTaCK members<br />

Count<br />

Push()<br />

Pop()<br />

Peek()<br />

Contains()<br />

desCriPTion<br />

The property Count returns the number of items in the stack.<br />

The Push() method adds an item on top of the stack.<br />

The Pop() method removes <strong>and</strong> returns an item from the top of the<br />

stack. If the stack is empty, an exception of type InvalidOperation<br />

Exception is thrown.<br />

The Peek() method returns an item from the top of the stack but does<br />

not remove the item.<br />

The Contains() method checks whether an item is in the stack <strong>and</strong><br />

returns true if it is.<br />

In this example, three items are added to the stack with the Push() method. With the foreach method, all<br />

items are iterated using the IEnumerable interface. The enumerator of the stack does not remove the items;<br />

it just returns item by item:<br />

var alphabet = new Stack();<br />

alphabet.Push('A');<br />

alphabet.Push('B');<br />

alphabet.Push('C');<br />

foreach (char item in alphabet)<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!