JonOfAllTrades
6/20/2008 8:57:00 PM
Good afternoon. I think I've gotten to the bottom of an issue that's been
frustrating me this afternoon, but I find the result somewhat astonishing.
Can anyone explain to me why this is desirable behavior?
I need to look up values based on four integer keys. I've written two- and
three-key dictionary wrappers before, but they just gracefully wrap nested
Dictionaries, but that seems silly with four keys. So I created a simple
struct, wrote a decent hash function (thanks, Jon Skeet!), and started
populating data.
But I get nothing back. Apparently Dictionary requires that keys be not
only equal, but *the same object* to be considered the same! I thought I was
working around that by using a struct; they should always be handled purely
as values, such that I could freely create a key once when loading data, and
again later when retrieving, and the Dictionary would never know the
difference.
Am I missing something? Is it because the structs are being boxed to become
keys?
Doh! Need to override Equals. I assumed that structs, being value types,
would compare on the basis of fields by default, like an old-school Union
construct. I assumed wrongly.
Here's hoping this helps someone!