how to implement override of GetHashCode() with logic of overriden Equals()
Solution 1
Firstly, as I think you understand, wherever you implement Equals
you MUST also implement GetHashCode
. The implementation of GetHashCode
must reflect the behaviour of the Equals
implementation but it doesn't usually use it.
See http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx - especially the "Notes to Implementers"
So if you take your example of the Item
implementation of Equals
, you're considering both the values of id
and name
to affect equality. So both of these must contribute to the GetHashCode
implementation.
An example of how you could implement GetHashCode
for Item
would be along the lines of the following (note you may need to make it resilient to a nullable name
field):
public override GetHashCode()
{
return id.GetHashCode() ^ name.GetHashCode();
}
See Eric Lippert's blog post on guidelines for GetHashCode
- http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/
As for whether you need to re-implement GetHashCode
in subclasses - Yes if you also override Equals
- as per the first (and main) point - the implementation of the two must be consistent - if two items are considered equal by Equals
then they must return the same value from GetHashCode
.
Side note: As a performance improvement on your code (avoid multiple casts):
if ( obj is Param){
Param p = (Param)(obj);
Param p = obj as Param;
if (p != null) ...
Solution 2
I prefer Josh Bloch's aproach.
Here's the example for the Param
class.
override GetHashCode(object obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + id.GetHashCode();
hash = hash * 23 + name.GetHashCode();
return hash;
}
}
Also, check this link out : .net - best algorithm for GetHashCode Properties used for the hashcode computation should be immutable as well.
rene
I've started with C++ programing in 2003 and continued with Java, C#, ...
Updated on May 07, 2020Comments
-
rene about 4 years
I have some classes as below, i have implemented the
Equals(Object)
method for almost all of them. But i don't know how to writeGetHashCode()
. As far I used these data types as value type in aDictionary
Collection, i think i should overrideGetHashCode()
.1.I don't know how to implement
GetHashCode()
with logic ofEquals(Object)
.2.There are some derived classes, if i override
GetHashCode()
andEquals(Object)
for base class (Param
), is it still necessary to override it for childs?class Param { ... public Int16 id { get; set; } public String name { get; set; } ... public override bool Equals(object obj) { if ( obj is Param){ Param p = (Param)(obj); if (id > 0 && p.id > 0) return (id == p.id); else if (name != String.Empty && p.name != String.Empty) return (name.equals(p.name)); else return object.ReferenceEquals(this, obj); } return false; } } class Item { public int it_code { get; set; } public Dictionary<String, Param> paramAr { get; set; } ... public override bool Equals(Object obj) { Item im = new Item(); if (obj is Item) im = (Item)obj; else return false; if (this.it_code != String.Empty && im.it_code != String.Empty) if (this.it_code.Equals(im.it_code)) return true; bool reParams = true; foreach ( KeyValuePair<String,Param> kvp in paramAr ){ if (kvp.Value != im.paramAr[kvp.Key]) { reParams = false; break; } } return reParams; } } class Order { public String or_code { get; set; } public List <Item> items { get; set; } ... public override bool Equals( Object obj ){ Order o = new Order(); if (obj is Order) o = (Order)obj; else return false; if (this.or_code != String.Empty && o.or_code != String.Empty) if (this.or_code.Equals(o.or_code)) return true; bool flag = true; foreach( Item i in items){ if (!o.items.Contains(i)) { flag = false; break; } } return flag; } }
EDIT: i get this warning:
Warning : 'Item' overrides Object.Equals(object o) but does not override Object.GetHashCode()
-
rene over 12 yearswhat about
order
class,it has just an id and a list, i can't use all of values in its list to make a hashcode. -
kaj over 12 yearsA List object has a
GetHashCode
implementation which may be sufficient for your purposes. Because the list affects equality you HAVE to consider it in theGetHashCode
implementation. However looking again at yourEquals
implementation, you're using them in a hierarchical sense - if ids match then the objects are equal regardless of their name values. So theGetHashCode
implementation would need to be different from my initial suggestion; I haven't worked out how though... (yet) -
Servy over 12 years@rene If that's what you're doing in Equals then yes, that's exactly what you need to do.
-
Servy over 12 years@KAJ The List's GetHashCode is going to be based on the reference of the list, not its contents. Two different lists with identical items won't necessarily have the same hash code. Now if you defined equality for Orders to be just based on the order code, and not on the items, then these problems go away. The Equals can just compare the order code and the getHashCode can just return the hash code of the order code. If the program needs to support having two different orders with the same order code and different items you then need to use each item in the list in both equals and GetHashCode.
-
kaj over 12 years@Servy: That's what I thought (was about to play with a proof of concept). The basic issue is,
GetHashCode
is supposed to be very quickly evaluated so iterating all items in a list doesn't sound like a good idea; however if its part of the test for equality, it has to be included. -
rene over 12 years@Servy "If the program needs to support having two different orders with the same order code and different items..." no it is not needed. i just want to check that the user don't add another order into databse with same items but different code, or reverse!
-
Servy over 12 yearsI suppose the other option would be to have GetHashCode just return the hash of order code. As long as you can ensure that no orders that are the same will ever have different order codes it technically meets the requirements, and as long as it is rare/impossible for two different orders to have the same order code it's still reasonably effective at balancing. Technically if a group of different items all share a hashcode, as long as the Equals method really does check equality, you just have a higher collision rate but still have a working Dictionary.