Why doesn't Tuple or KeyValueItem have a setting?

I need a structure containing a pair of values ​​from which the value will be changed. So my first thought was to use KeyValueItem or Tupple <,> but then I saw that they only have a getter. I do not understand why? What would you use in my case? I could create my own class, but is there any other way?

+6
source share
3 answers

They are immutable types. The idea of ​​immutable types is that they are valuable and therefore cannot change. If you need a new value, you create a new one.

Say the first value of your tuple should change, just do the following:

myValue = Tuple.Create(newValue, myValue.Item2); 

To understand why immutability is important, consider a simple situation. I have a class that says it contains minimum and maximum temperatures. I could save this as two values ​​and provide two properties to access them. Or I could store them as a tuple and provide one property that this tuple supplies. If the tuple was changed, another code could change these minimum and maximum values, which would mean changing min and max inside my class. By making the tuple invariable, I can confidently pass both values ​​at once, being sure that the other code cannot be simulated.

+8
source

You can create your own implementation:

 public class Pair<T, U> { public Pair() { } public Pair(T first, U second) { this.First = first; this.Second = second; } public T First { get; set; } public U Second { get; set; } }; 
+2
source

Tuples are read only in C #. This is explained in the answer here , mainly because of their nature from functional programming.

You must create your own implementation of MutableTuple , which allows you to change.

What to consider:

  • You can override Equals and GetHashCode
  • You might want to sort it by the First element of the tuple ( IComparable ).
0
source

Source: https://habr.com/ru/post/957178/


All Articles