Generic Stack


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents

LIFO

The Stack class allows the implementation of a LIFO(Last-In-First-Out) storage system.

Image:FILO.gif

Due to Stack being a collection it can easily be simulated using a List. This is handy to remember so that if find yourself trying to implement such a system just remember that one already exists!

Generic.Stack vs Stack

The Collections.Generic.Stack should always be chosen over the Collections.Stack class to promote type safety. However, their basic operation is identical in every area apart from when using an enumerator.


Usage of Generic Stack

System.InvalidOperationException thrown if no check for within bounds.

byte data = 42;
Stack<byte> myStack = new Stack<byte>();
 
myStack.Push(data);
 
if (myStack.Count > 0) //Check within bounds
{
   data = myStack.Pop();
}

Simulation of Generic Stack using Generic List

Note that by simulating a stack like this means that all elements are open for access and therefore the stack can be abused.

System.ArgumentOutOfRangeException thrown if no check for within bounds

byte data = 42;
List<byte> myList = new List<byte>();
 
myList.Insert(0, data); //PUSH
 
if (myList.Count > 0) //Check within bounds
{
   //POP
   data = myList[0];
   myList.RemoveAt(0);
}

Enumerator

The Enumerator or more precisely the Stack<T>.Enumerator allows simple iteration through the elements of the stack.

Note: To protect the stack from abuse the enumerator only allows read operations.

Unlike the IEnumerator (returned by Collections.Stack) the Stack<T>.Enumerator does not provide a Reset method.

The most important thing to remember when using an enumerator is not to modify the stack once an instance of the enumerator has been created. Therefore the fool-proof way of ensuring this is to stick it inside its own method.


using System;
using System.Collections.Generic;
 
static void stackEnumeratorEG()
{
   Stack<byte> myStack = new Stack<byte>();
 
   myStack.Push(1);
   myStack.Push(2);
   myStack.Push(3);
   myStack.Push(4);
 
   stackPrint(myStack);
 
   myStack.Pop();
   myStack.Pop();
 
   stackPrint(myStack);
}
 
static void stackPrint(Stack<byte> myStack)
{
  Stack<byte>.Enumerator msEnumerator = myStack.GetEnumerator();
 
  while (msEnumerator.MoveNext())
  {
     Console.WriteLine(msEnumerator.Current.ToString());
  }
  Console.WriteLine();
}

The alternative is to use a foreach statement which uses the enumerator behind the scenes.

MSDN Documentation


Previous_Page_.gif Next_Page_.gif


Personal tools