Reputation: 875
Why two object's hash code is not same even though they have similar values. What is the other best approach to find value equality among objects with out reading ones each property and have check with other ones property?
Person person = new Person();
person.Name = "X";
person.Age = 25;
person.Zip = 600056;
person.Sex = 'M';
Person person1 = new Person();
person1.Name = "X";
person1.Age = 25;
person1.Zip = 600056;
person1.Sex = 'M';
int hashCode1 = person1.Name.GetHashCode();
int hashCode = person.Name.GetHashCode();
// hashCode1 and hashCode values are same.
if (person.GetHashCode() == person1.GetHashCode())
{
// Condition is not satisfied
}
Upvotes: 0
Views: 218
Reputation: 133
in your code hashCode1 == hashCode is true because hashing same string will always give you the same result. however insances are different so you have to override GetHashCode() in a way that fits your business logic for example
public override int GetHashCode()
{
return Name.GetHashCode() ^ Zip.GetHashCode() ^ Sex ^ Age;
}
I sugest you take a look at this answer GetHashCode Guidelines in C#.
and http://musingmarc.blogspot.com/2007/08/vtos-rtos-and-gethashcode-oh-my.html
Upvotes: 3
Reputation: 8352
In your example, both objects are alike but not the same. They are different instances, so they have different hash code. Also person1 == person2 and person1.Equals(person2) are false.
You can override this behavior. If you consider the two objects are the same if those properties are equal, the you can:
public override bool Equals(object other) {
if(other == this) return true;
var person = other as Person;
if(person == null) return false;
return person.Name == Name && person.Age == Age && person.Zip == Zip && person.Sex == Sex;
}
public override int GetHashCode() {
//some logic to create the Hash Code based on the properties. i.e.
return (Name + Age + Zip + Sex).GetHashCode(); // this is just a bad example!
}
Upvotes: 2
Reputation: 9340
Why two object's hash code is not same even though they have similar values
Because that's the expected way of identifying them uniquely. AFAIK, most frameworks/libraries uses the pointer value for this by default.
What is the other best approach to find value equality among objects with out reading ones each property and have check with other ones property?
Depends on what makes them "equal", according to your needs. Basically it's still comparing properties, but maybe just more limited.
Upvotes: 1