Generic Class Example (Stack)

CSharp · Console

/Program.cs

using System;

public class Stack<T> {
  readonly int max_size;
  int index = 0;
  public int size { get; set; }
  T[] items = null;

  public Stack() : this(100) { } // default max_size of 100

  public Stack(int size) {
    max_size = size;
    items = new T[max_size];
  }

  // Push - Adds item to the top of the stack
  public void Push(T item) {
    if (size >= max_size)
      throw new StackOverflowException();

    items[index++] = item; // adds item in next spot
    size++; // increments actual size
  }

  // Pop - returns item from top and then removes it from the stack
  public T Pop() {
    if (size <= 0)
      throw new InvalidOperationException("Stack is empty, cannot Pop");

    size--;
    return items[--index]; // decrements by 1 and returns value at index
  }

  // Peek - returns the last item in the listt
  public T Peek() {
    return items[index - 1];
  }

  // Get - returns the value of the specified index
  public T Get(int idx) {
    return items[idx];
  }
}

public class Program
{
  public static void Main() {
    Stack<string> StarWars = new Stack<string>();
    StarWars.Push("The Phantom Menace");
    StarWars.Push("Attack of the Clones");
    StarWars.Push("Revenge of the Sith");
    StarWars.Push("Rogue One");
    StarWars.Push("Solo");
    StarWars.Push("A New Hope");
    StarWars.Push("The Empire Strikes Back");
    StarWars.Push("Return of the Jedi");
    StarWars.Push("The Force Awakens");
    StarWars.Push("The Last Jedi");
    StarWars.Push("The Rise of Skywalker");

    Console.WriteLine("Size of Stack: {0}", StarWars.size); // 11
    Console.WriteLine(StarWars.Peek()); // The Rise of Skywalker
	Console.WriteLine(StarWars.Pop());  // The Rise of Skywalker
    Console.WriteLine(StarWars.Pop());  // The Last Jedi
    Console.WriteLine(StarWars.Peek()); // The Force Awakens
    Console.WriteLine(StarWars.Get(5)); // A New Hope
    Console.WriteLine("Size of Stack: {0}", StarWars.size); // 9
  }
}
;