Shawn Mclean
Shawn Mclean

Reputation: 57469

Dictionary<Key,Value> - key cannot be class?

I'm using a Vector3 - contains properties X,Y,Z as a key in a dictionary. Lets say I already added to the dictionary (myDic) a Vector3 with values (0,0,0).

Then I do this:

Vector3 vec = new Vector3(0,0,0);
if (!myDic.ContainsKey(vec))
{
    //Should never reach here.
}

I also created overload operators for == and != for the Vector3 class.

It reaches there anyways. Is there a problem when using an object like a Vector3 to be the key for a dictionary?

Upvotes: 1

Views: 2221

Answers (2)

user166390
user166390

Reputation:

You are implementing it wrong :)

In short, you need to implement Equals and GetHashCode: == and != are irrelevant here as they are not used.

The reason == and != are not used is that they, like all operators, are non virtual and the "constraint" for the K in IDictionary<K,V> is object (not specified, really). Therefore, only the (virtual) methods valid for all objects (which includes all sub-types of object) such as Equals and GetHashCode can be used in a polymorphic fashion here.

See Example of Dictionary collection with custom class as key? for a working example with test-case.

Happy coding.

Upvotes: 4

Anthony Pegram
Anthony Pegram

Reputation: 126884

You need to override GetHashCode and Equals inside your class. The dictionary works on the combination of both, with the first check being the hash and the clincher being Equals. Providing a custom implementation for == is not going to do anything for your dictionary.

If you are unable or unwilling to override these methods within the class itself, your other option is to implement an IEqualityComparer<YourClass> and provide an instance of the implementation in the dictionary constructor. It will be within this implementation that you will provide code for the aforementioned methods.

Upvotes: 6

Related Questions