[Mono-dev] A bug? On Mono we can't use delegate as the dictionary key

Matt Guo matt at mattguo.com
Wed Nov 25 08:24:06 EST 2009


Hey, all,

Today I was stucked by a strange problem for several hours, in a word,
we can't use delegate (including delegates form
normal methods, annonymous methods and lambda) as the dictionary key.
It works on .Net, but not on Mono. The reason is that on Mono,
delegate.GetHashCode () can change: initially the hash code is 0, then
after the delegate's first invokation the hash code will become
non-zero (and shall be the address of the method).
So is that a bug of mono? (I used the latest Mono 2.4 release)

Following example explains everything.

[Code]

                       Dictionary <EventHandler, int> dict = new
Dictionary<EventHandler, int> ();
                       List <EventHandler> list = new List<EventHandler> ();

                       EventHandler handler = (s, e) => Console.WriteLine (s);
                       dict.Add (handler, 0);
                       list.Add (handler);
                       Console.WriteLine ("{0}, {1}, {2}",
handler.GetHashCode(),
dict.ContainsKey (handler), list.Contains (handler));
                       //Call delegate
                       handler (null, EventArgs.Empty);
                       Console.WriteLine ("{0}, {1}, {2}",
handler.GetHashCode(),
dict.ContainsKey (handler), list.Contains (handler));

[Mono Output]
0, True, True
-1215724864, False, True

[.Net Output]
1881641292, True, True
1881641292, True, True


-- 
B.R.
GUO Rui (Matt)


More information about the Mono-devel-list mailing list