ITQuants blog

Sample of using GetHashCode with System.Collections.HashTable

Mar 7

Written by:
3/7/2012 11:34 AM  RssIcon

Just to give a sample on how to use it on classes containing several fields as keys. This sample is using as key a string field and datetime one.

For instance, in order to use some code which should look like that: 

1.MessageId _msg = new MessageId();
2._msg.Id = id;
3._msg.Posted = ((Post)m_posts[0]).Posted;
4.if (m_generatedMessages.Contains(_msg))

We have to define the GetHashCode using the ^ operator: 

 
1.public override int GetHashCode()
2.{
3.     return Id.GetHashCode()^Posted.GetHashCode();
4.}

And for the other operators: 

 
01.public static bool operator<(MessageId m1, MessageId m2)
02. 
03.{
04. 
05.if(m1.Id!=m2.Id)
06. 
07.return m1.Id.CompareTo(m2.Id)>0;
08. 
09.else
10. 
11.return m1.Posted < m2.Posted;
12. 
13.}
14. 
15.public static bool operator >(MessageId m1, MessageId m2)
16. 
17.{
18. 
19.if (m1.Id != m2.Id)
20. 
21.return m1.Id.CompareTo(m2.Id)<0;
22. 
23.else
24. 
25.return m1.Posted > m2.Posted;
26. 
27.}
28. 
29.public static bool operator ==(MessageId m1, MessageId m2)
30. 
31.{
32. 
33.return m1.Id == m2.Id && m1.Posted == m2.Posted;
34. 
35.}
36. 
37.public static bool operator!=(MessageId m1, MessageId m2)
38. 
39.{
40. 
41.return m1.Id != m2.Id || m1.Posted != m2.Posted;
42. 
43.}
44. 
45.public override bool Equals(object o)
46. 
47.{
48. 
49.try
50. 
51.{
52. 
53.return (bool)(this == (MessageId)o);
54. 
55.}
56. 
57.catch
58. 
59.{
60. 
61.return false;
62. 
63.}
64. 
65.}

1 comment(s) so far...


Gravatar

Re: Sample of using GetHashCode with System.Collections.HashTable

Indeed, after test, the best is to use IComparable and the CompareTo methods. When using the GetHashCode method with a lot of items, I got some surprises since it was unable to find some items which were in the dictionary.

By Ph. Bonneau on   4/12/2012 4:08 PM

Search blog