I Finally Used a Tuple!

April 13, 2012

Tuples have been the most distracting thing since introduced in .NET. I’ve tried to use them a few times, but they always end up annoying me. One time I wondered if I could sublcasss a Tuple and give it some named properties and simplify the declarations when I use it. That got to the point of “why bother use the tuple, then?”

Finally, last night, I found a place to use one that seems to fit pretty well without being annoying. It’s local-scope only. Maybe that’s the important thing about it.

   1: var states = this.childBuses.Select(bus => new Tuple<BusRegistration, BusMessage>(bus, message));

   2: foreach (var state in states)

   3: {

   4:     Task.Factory.StartNew(

   5:         m =>

   6:             { 

   7:                 var msg = (Tuple<BusRegistration, BusMessage>)m;

   8:                 var client = new NetTcpBusClient(msg.Item1.Address);

   9:                 client.SendPublishDown(msg.Item2);                            

  10:             },

  11:         state);

  12: }

It worked well there, so I did it again in another place.

I need two pieces of data within my task, but you can only pass in one state object. I created a state object with a couple of properties, and that worked fine. But then I had to do it again elsewhere, and creating another state object seemed wrong. (I suppose I could’ve done new object[] { a, b}).

So, I revisited the blasted Tuple, and at last I used it without hating it. In fact, it works pretty well.