I needed a structure that contains a pair of values, of which ones value would be changed. So my first thought was to use a KeyValueItem or a Tupple<,> but then I saw that they have only a getter. I can't realize why? What would you use in my case? I could create my own class, but is there any other way?
They are immutable types. The idea of immutable types is that they represent a value, and so cannot change. If you need a new value, you create a new one.
Let's say the first value of your tuple needs to change, just do this:
myValue = Tuple.Create(newValue, myValue.Item2);
To understand why immutability is important, consider a simple situation. I have a class that say contains a min and max temperatures. I could store that as two values and provide two properties to access them. Or I could store them as a tuple and provide a single property that supplies that tuple. If the tuple were mutable, other code could then change these min and max values, which would mean the min and max inside my class will have changed. By making the tuple immutable, I can safely pass out both values at once, secure in the knowledge that other code can't tamper with them.
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; }
};
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