dictionary "duplicate class key" C# RRS feed

  • Question

  • Everything is C#, VS 2010, .Net 4.0

    I created a class MyKey : IEqualityComparer<MyKey> (int, DateTime) and a dictionary : Dictionary<MyKey, MyValue> = new Dictionary<MyKey, MyValue();

    I then added multiple dictionary entries with exactly the same key(MyKey(int, DateTime) (but different instances) and MyValue. No exceptions until I added the same instance of the key. That implies to me that the actual comparison is based not of the values in the key, but on the reference to it. Changing the value of the int in MyKey also throws an exception, which supports my conclusion.

    Removing the IEqualityComparer has no effect.

    Have I got this wrong? I may still be thinking too much in C++ terms.



    Monday, August 11, 2014 4:24 PM


  • My bad. Still thinking too much in C++. The C# dictionary object keeps references to the key, and doesn't pay any attention to the values.
    • Marked as answer by roadkill4299 Tuesday, August 12, 2014 8:37 PM
    Tuesday, August 12, 2014 8:37 PM

All replies