Wednesday, July 17, 2013

Is it immoral to use a KeyValuePair like a Tuple in C#?

An Array is sort of like a pill packet of Sudafed in that everything contained in the collection is of the same type as defined by the collection itself. In a pack of Sudafed all of the pills will be Sudafed pills. But what if you need to take different sorts of pills (not necessarily a bad reflection upon you) and yet you want to keep all of your pills contained together. Well, those plastic containers for the seven different days of the week seem pretty cool for that.

With such a container one could keep up to seven different pills separate in a greater collection. In a Tuple one may keep up to seven different objects of any type together so the Tuple matches up to a pill box in my analogy. The Tuple is really handy in C# for handing more than one thing back from a method which will only technically return one thing. This hacky way of beating the Thunderdome problem has always seemed a lot cleaner to me than using ref and out variables, and I have fallen in love with Tuples. However, today I was told I had to downgrade a WinForms app I recently made in ASP.NET 4.5 to run in ASP.NET 3.5. When I did so I found I could not use a Tuple so I put my pills in my contact lens case instead.

If you think about when you use Tuples, you may realize that majority of the time you are making a Tuple that holds two things in lieu of three to seven things. I have never needed a Tuple that is seven items in size, but I use Tuples that are two items long all the time. (Example: I want to hand back from my method the ideal output of whatever type and a placeholder for a string value for an exception error message which could arise within the method.) If you are like me you are experiencing the same thing: Tuples with fewer items come out in your code more frequently than Tuples with more items. This means that probably more often than not, you may "use Tuples" in older versions of C# by just using a KeyValuePair type in lieu of a Tuple type. This is NOT what a KeyValuePair is intended for and you may only store up to two items in a KeyValuePair in lieu of up to seven, but:

  1. it works
  2. you only need two slots most of the time

Is this a dirty hack? Well consider this question: Are Tuples themselves a dirty hack and is this any worse?

No comments:

Post a Comment