Information Technology Reference
In-Depth Information
The Stack Example Using Generics
The following code shows the stack example implemented using generics. Method Main
defines two variables: StackInt and StackString . The two constructed types are created using
int and string as the type arguments.
class MyStack<T>
{
T[] StackArray;
int StackPointer = 0;
public void Push(T x) {
if ( !IsStackFull )
StackArray[StackPointer++] = x;
}
public T Pop() {
return ( !IsStackEmpty )
? StackArray[--StackPointer]
: StackArray[0];
}
const int MaxStack = 10;
bool IsStackFull { get{ return StackPointer >= MaxStack; } }
bool IsStackEmpty { get{ return StackPointer <= 0; } }
public MyStack() {
StackArray = new T[MaxStack];
}
public void Print() {
for (int i = StackPointer -1; i >= 0 ; i--)
Console.WriteLine(" Value: {0}", StackArray[i]);
}
}
Search WWH ::




Custom Search