Generic Pop and Push for List<T>
- by Bil Simser
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:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, "Courier New", Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
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.