Posts Tagged ‘equals’

How I write Equals and GetHashCode in csharp

April 25th, 2014

My code is copied with pride from the net.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
///
This is standard overridden Equals method.
/// Code is copied with pride from
/// http://msdn.microsoft.com/en-us/library/336aedhh(v=vs.85).aspx
///

//////
public override bool Equals(object obj)
{
if (null == obj || GetType() != obj.GetType())
{
return false;
}
var b = (MyType)obj;
return
this.Property1 == b.Property1 &&
...
this.PropertyN == b.PropertyN;
}

///
This is the ordinary overriden GetHashCode
/// with code proudly copied from
/// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
///

///
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
const int Salt = 23;
var hash = 17;
hash = hash + Salt * Property1.GetHashCode();
...
hash = hash + Salt * (null == PropertyN ? 0 : PropertyN.GetHashCode());  // Nullable values has to be taken care of.
return hash;
}
}