Csharp/CSharp Tutorial/Generic/Generic Stack
Generic Stack based on generic Array
<source lang="csharp">using System; using System.Collections.Generic; class MyStack<T> {
int MaxStack = 10; T[] StackArray; int StackPointer = 0; public MyStack() { StackArray = new T[MaxStack]; } public void Push(T x) { if (StackPointer < MaxStack) StackArray[StackPointer++] = x; } public T Pop() { return (StackPointer > 0) ? StackArray[--StackPointer] : StackArray[0]; } public void Print() { for (int i = StackPointer - 1; i >= 0; i--) Console.WriteLine(" Value: {0}", StackArray[i]); }
} class MainClass {
static void Main() { MyStack<int> StackInt = new MyStack<int>(); MyStack<string> StackString = new MyStack<string>(); StackInt.Push(3); StackInt.Push(7); StackInt.Print(); StackString.Push("This is fun"); StackString.Push("Hi there! "); StackString.Print(); }
}</source>
Value: 7 Value: 3 Value: Hi there! Value: This is fun
Push and pop value in a generic Stack<T>
<source lang="csharp">using System; using System.Collections.Generic;
class MainClass {
public static void Main() { Stack<string> st = new Stack<string>(); st.Push("One"); st.Push("Two"); st.Push("Three"); st.Push("Four"); st.Push("Five"); while(st.Count > 0) { string str = st.Pop(); Console.Write(str + " "); } Console.WriteLine(); }
}</source>
Five Four Three Two One
Use generic Statck to store your own class
<source lang="csharp">using System; using System.Collections.Generic;
class MainClass {
public static void Main(string[] args) { // Create and use a Stack of Assembly Name objects Stack<MyClass> stack = new Stack<MyClass>(); stack.Push(new MyClass()); MyClass ass3 = stack.Pop(); Console.WriteLine("\nPopped from stack: {0}", ass3); }
} class MyClass {
public override string ToString(){ return "my class"; }
}</source>
Popped from stack: my class