Skip to main content

Abusing using

When we went from unmanaged to managed languages we got rid of the headache of having to do manual memory management. Unfortunately that meant we also lost destructors and with them the ability to do some nice tricks. Luckily we can still do some of these tricks with the using keyword. Lets take a look

One of the nice things you could do with destructors in c++ was to tie the execution of a piece of code to the scope of a variable. You did this by putting the piece of code in a destructor of some object, every time you instantiated that object on the stack you were assured your code would be run when that object left scope.

But wait, we still can do this with using and IDisposable.

Oh boy! Silly example time!

Lets say you’ve got a bunch of freeloading friends. You kept score on how many rounds of beer you bought last night in a dictionary and now you want to confront them with the ugly truth by putting the contents of that dictionary online in an html table.

var rounds = new Dictionary<string,int> {{"Me", 6}, {"Bill", 3}, {"Pete", 1}};

Formatting html tables can be a lot of busywork. You need to keep track of all elements. Every <td> needs a </td>. This can get messy fast!

First we create a helper class that will print and keep track of elements:

   1: class HtmlElement : IDisposable
   2: {
   3:     private string Element;
   5:     public HtmlElement(string element)
   6:     {
   7:         Element = element;
   8:         Console.WriteLine("<{0}>", Element);
   9:     }
  11:     public void Dispose()
  12:     {
  13:         Console.WriteLine("</{0}>", Element);
  14:     }
  15: }

Now printing tables (or any kind of simple html) is easy.

   1: using(new HtmlElement("table"))
   2:     foreach (var row in rounds)
   3:         using (new HtmlElement("tr"))
   4:         {
   5:             using (new HtmlElement("td")) Console.WriteLine(row.Key);
   6:             using (new HtmlElement("td")) Console.WriteLine(row.Value);
   7:         }

Every html element we print is tied to the scope of the using block it’s in. When we get to the end of the block the closing element is automatically added. Simple and pretty readable.

I’ve seen this trick used in all kinds of places where you want a piece of code guaranteed to run after some other operation. Transactions in nHibernate use the same mechanism for example. Keeps you from typing catch/finally blocks around every transaction.


Popular posts from this blog

Marshalling strings with StringBuilder

The dotNet framework is pretty smart when it comes to marshalling managed to unmanaged datatypes for PInvoke calls. When you want to pass a Guid from the managed to the unmanaged world the framework knows how to transform the .Net Guid structure to a Windows GUID without you even asking for it.

Agile architecture, embrace change by reducing complexity

Software development can sometimes be very counterintuitive. For example, when people started building larger software systems halfway through the last century one of the things they discovered was that changing existing software is often far more difficult and error prone than building new software. Most developers rediscover this somewhere in their first year of being a professional developer. They start out with a new project and as time goes by changes start taking more and more time, this can be very hard to explain to a client and usually we don’t until we get completely stuck and tell the client we need to start from scratch. I think this practice has been responsible for most of the bad reputation software development has.

Square One available on the Android market

This is just a short post to let you know that a first version of the Android app I’ve been working on for the last couple of weeks is available on the Android market. The app is called Square One and it’s a simple bassline synthesizer. It’s free so try it out and let me know what you think of it, but be prepared it’s still an early version. I hope to add more features in the next few months and maybe build something that can be used to create real music.The lower part of the screen contains the sequencer controls that can be used to program your own bass lines. On the left is a four by four grid of buttons where you can select a step in the sequence. On the right you can select the note to be played on that step. When you’re done you can press Start and the sequence starts playing. The knobs on the top can be used to control a couple of parameters from the synthesizer engine that creates the sound. You can control the cutoff frequency and resonance of the low-pass filter, attack and …