Generic Pop and Push for List<T>

Posted by Bil Simser on ASP.net Weblogs See other posts from ASP.net Weblogs or by Bil Simser
Published on Thu, 13 Jan 2011 16:21:00 GMT Indexed on 2011/01/13 16:54 UTC
Read the original article Hit count: 195

Filed under:

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.

© ASP.net Weblogs or respective owner

Related posts about .NET