Stack ’em up!

OK, clearly I have been remiss in my bloging duties and owe you all some code.  To be fair, it’s because I’m head down developing a brand new platform that will form the basis of our future products and it really has been all go.

One of the most fundamental structures in programming languages is the stack.  It’s an insanely useful structure, particularly for analysing hierarchical data, but also for removing recursion from code (because recursion is oft times bad).

C# has a handy generic  Stack  class – which can be used like so-

Basically, you push things onto the top of the stack, and pop them off later.  It’s amazing what you can do with such a simple concept, but that’s not the topic of this post.

When you start doing more complex operations, you often find you want to put quite a bit of data onto the stack, rather than just a simple class.  I often find, in this particular scenario, it’s time to create a custom class/struct to hold the data.  However, sometimes, you just need something really simple.  It’s at times like those our old friend the Tuple comes in handy.  However, the code starts looking really unwieldy alarmingly quickly-

We can solve this really easily though, by extending Stack  to support multiple values:

Now we can write the same code in a much nicer way:

Simple, but very effective.  Let me know if it helps you out in the comments below.

Leave a Reply

%d bloggers like this: