I'm thinking this could be a convenient dictionary:
var myDict = new Dictionary<(int, int), bool>();
What would the hashes look like?
What would the equivalent key type (struct) look like?
Answer. Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system. The following code example shows a dictionary with keys representing a simple x,y grid system.
A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.
A value tuple is a data structure that has a specific number and sequence of values. The ValueTuple<T1> structure represents a value tuple that has one element. The value tuple types differ from the tuple types (such as Tuple<T1> as follows: They are structures (value types) rather than classes (reference types).
Yes, that's fine. The ValueTuple<...>
family is a well-defined set of regular structs with the correct equality and hash-code behaviour to work as dictionary keys. There is a slight caveat in that they are mutable rather than immutable, but that doesn't really impact them in this context thanks to copy semantics (which means: you can't change the key after it has been added, as you're only changing a different copy of the key; this is very different to the problem with mutable classes as keys). You can see the code here.
Being a value type, the hash for ValueTuple
follows the default implementation, which is based on the values of the members:
If value types do not override GetHashCode, the ValueType.GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes.
Tuples are mutable, but because they are copied by value, you can use them safely as dictionary keys. A problem might be if you use a variable of a tuple type, use this variable in Dictionary.Add
, then modify this variable and try to access the associated value from the dictionary using the same variable as a key. In this case you will not find it in the dictionary.
The equivalent structure would be like:
MyStruct : struct { public int A; public int B; }
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