Tuples are nice for expressing whole-values. But it has a penalty on readability, 'Item1' and 'Item2' is not so intuitive. To improve the latter I introduced a class-alias like below. I was wondering if someone got a better solution. It still needs a 'dedicated' class anyway. The example below is naïve, it just points out the problem.
enum Unit { Celsius, Fahrenheit }
class Temperature: Tuple<decimal, Unit>
{
public decimal Value
{
get { return Item1; }
}
public Unit
{
get { return Item2; }
}
public Temperature(decimal item1, Unit item2)
: base(item1, item2)
{
}
}
// pseudo
var temp = new Temperature(37, Unit.Celsius);
temp.Item1 == temp.Value == 37;
temp.Item2 == temp.Unit == Unit.Celsius;
What you've done above is basically create a class with two read-only properties, they just happen to use Tuple as a backing store.
The problem you highlight is not one the Tuple aims to fix. Tuple is there to provide a generic construct for wrapping values in to an object where defining a class is deemed too much effort. I don't personally rate them and limit them to within a method scope, however anonymous types are better suited - I certainly wouldn't want a return type of Tuple for the exact reason you're highlighting.
If you want to have a read/write class with named properties, create a class (or struct).
C# 6 is going to introduce a new syntax for "primary constructors" which will substantially simplify classes such as your class Temperature
.
For example:
public sealed class Temperature(decimal value, Unit unit)
{
public decimal Value { get; } = value;
public Unit Unit { get; } = unit;
}
In the future, you should be able to use that approach instead. (I'm not going to debate whether that's a good thing or not though!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With