Key compare in Dictionary

David Nicholson <[email protected]> Thu, 20 May 2010 06:32:46 -0400
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
I am using a class as a key to a Dictionary, and the key comparisons are =
not working as I expect. The example below illustrates:

// This is the key of the dictionary
namespace DictionaryTest
{
    using System;
    public class KeyData : IEquatable<KeyData>
    {
        public string F1 { get; set; }
        public int F2 { get; set; }

        public KeyData(string f1, int f2)
        {
            F1 =3D f1;
            F2 =3D f2;
        }

        bool IEquatable<KeyData>.Equals(KeyData other)
        {
            if (String.Compare(F1, other.F1, true) !=3D 0)
                return false;

            if (F2 !=3D other.F2)
                return false;

            return true;
        }
    }
}

and I am using it like this:

namespace DictionaryTest
{
   using System;
   using System.Collections.Generic;
    class Program
    {
        static void Main(string[] args)
        {
            var d1 =3D new Dictionary<KeyData, int>();

            d1.Add(new KeyData("a", 1), 1);
            d1.Add(new KeyData("b", 1), 1);

            KeyData kd =3D new KeyData("a", 1);

            string mesg;
            if (d1.ContainsKey(kd))
                mesg =3D "Found";
            else
                mesg =3D "Not found";

            Console.WriteLine(mesg);
        }
    }
}

This always returns "Not found", which isn't what I expect. A breakpoint =
on KeyData.Equals is never reached. The documentation for dictionary incl=
udes:

"If type TKey implements the System .IEquatable <T> generic interface, th=
e default equality comparer uses that implementation"

I wrote an IEqualityComparer<KeyData> and passed that to the dictionary c=
onstructor, and it works as I expect.

Thanks
David.

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives