Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a Tuple, or a KeyValueItem, don't have a setter?

Tags:

c#

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?

like image 847
Kobe-Wan Kenobi Avatar asked Nov 01 '13 10:11

Kobe-Wan Kenobi


2 Answers

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.

like image 162
David Arno Avatar answered Nov 03 '22 14:11

David Arno


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; }
};
like image 33
Dzmitry Martavoi Avatar answered Nov 03 '22 12:11

Dzmitry Martavoi