Search code examples
c#dictionaryvaluetuple

Are ValueTuples suitable as dictionary keys?


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?


Solution

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