Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ValueTuples suitable as dictionary keys?

Tags:

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?

like image 881
Steinbitglis Avatar asked Dec 18 '18 10:12

Steinbitglis


People also ask

Can tuple be used as dictionary key in C#?

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.

Can we use tuple as key in dictionary python?

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.

What is System ValueTuple?

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).


2 Answers

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.

like image 122
Marc Gravell Avatar answered Nov 22 '22 07:11

Marc Gravell


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; } 
like image 25
Nick Avatar answered Nov 22 '22 07:11

Nick