Readability and Tuples in C #

Tuples are good for expressing integer values. But he has a penalty for readability, "Item1" and "Item2" are not so intuitive. To improve on the latter, I introduced a class alias as shown below. I was wondering if anyone has a better solution. One way or another, a "dedicated" class is still needed. The example below is naive, it simply indicates a 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;
+4
source share
2 answers

What you did above basically creates a class with two read-only properties, they just use Tuple as their backup storage.

, , - , Tuple. Tuple , . , - , , Tuple , .

/ , ( ).

+9

# 6 " ", , class Temperature.

:

public sealed class Temperature(decimal value, Unit unit)
{
    public decimal Value { get; } = value;
    public Unit    Unit  { get; } = unit;
}

. ( , , !)

+8

All Articles