Build your own stack using generic List - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Build your own stack using generic List

Demo Code

using System;// w ww  .  j  a  v  a2s .c  o  m
using System.Collections.Generic;
using System.Text;
public class MyStack<T>
{
   private List<T> _list = new List<T>();
   public void Push(T value)
   {
      _list.Add(value);
   }
   public bool IsEmpty()
   {
      return _list.Count == 0;
   }
   public T Pop()
   {
      if(IsEmpty())
      {
         throw new InvalidOperationException("Stack is empty");
      }
      T value = _list[_list.Count - 1];
      _list.RemoveAt(_list.Count - 1);
      return value;
   }
}
class Program
{
   static void Main(string[] args)
   {
      MyStack<string> names = new MyStack<string>();
      names.Push("A");
      names.Push("B");
      names.Push("C");
      while(!names.IsEmpty())
      {
         string name = names.Pop();
         Console.WriteLine(name);
      }
   }
}

Result


Related Tutorials