Generic Pop and Push for List<T>

Here's a little snippet I use to extend a generic List class to have similar capabilites to the Stack class.

The Stack<T> class is great but it lives in its own world under System.Object. Wouldn't it be nice to have a List<T> that could do the same? Here's the code:

   1:  public static class ExtensionMethods
   2:  {
   3:      public static T Pop<T>(this List<T> theList)
   4:      {
   5:          var local = theList[theList.Count - 1];
   6:          theList.RemoveAt(theList.Count - 1);
   7:          return local;
   8:      }
   9:   
  10:      public static void Push<T>(this List<T> theList, T item)
  11:      {
  12:          theList.Add(item);
  13:      }
  14:  }

It's a simple extension but I've found it useful, hopefully you will too! Enjoy.

3 Comments

Comments have been disabled for this content.