|
Listing 13-3 extracted from chapter
Generics
Listing 13-2< > Listing 13-4
This listing can be compiled with the command line: csc.exe /target:exe Example_13_3.cs Errors: 1 Warnings: 0
Example_13_3.cs
class Stack<T>{
private T[] m_ItemsArray;
private int m_Index = 0;
public const int MAX_SIZE = 100;
public Stack(){ m_ItemsArray = new T[MAX_SIZE]; }
public T Pop(){
if (m_Index ==0 )
throw new System.InvalidOperationException(
"Can't pop an empty stack.");
return m_ItemsArray[--m_Index];
}
public void Push(T item) {
if(m_Index == MAX_SIZE)
throw new System.StackOverflowException(
"Can't push an item on a full stack.");
m_ItemsArray[m_Index++] = item;
}
}
class Program{
static void Main(){
Stack<int> stack = new Stack<int>();
stack.Push(1234);
int number = stack.Pop(); // Don't need any awkward cast.
stack.Push(5678);
string sNumber = stack.Pop(); // Compilation Error:
// Cannot implicitly convert type 'int' to 'string'.
}
}
Copyright Patrick Smacchia 2006 2007
|