Equals and GetHashCode
suggest changeEach implementation of Equals
must fulfil the following requirements:
- Reflexive: An object must equal itself.
x.Equals(x)
returnstrue
. - Symmetric: There is no difference if I compare x to y or y to x - the result is the same.
x.Equals(y)
returns the same value asy.Equals(x)
. - Transitive: If one object is equal to another object and this one is equal to a third one, the first has to be equal to the third.if
(x.Equals(y) && y.Equals(z))
returnstrue
, thenx.Equals(z)
returnstrue
. - Consistent: If you compare an object to another multiple times, the result is always the same.Successive invocations of
x.Equals(y)
return the same value as long as the objects referenced by x and y are not modified. - Comparison to null: No object is equal to
null
.x.Equals(null)
returnsfalse
.
Implementations of GetHashCode
:
- Compatible with
Equals
: If two objects are equal (meaning thatEquals
returns true), thenGetHashCode
must return the same value for each of them. - Large range: If two objects are not equal (
Equals
says false), there should be a high probability their hash codes are distinct. Perfect hashing is often not possible as there is a limited number of values to choose from. - Cheap: It should be inexpensive to calculate the hash code in all cases.
See: Guidelines for Overloading Equals() and Operator ==
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
2 Literals
6 Equals and GetHashCode
18 Regex
19 DateTime
20 Arrays
22 Enum
23 Tuples
25 GUID
26 BigInteger
28 Looping
29 Iterators
30 IEnumerable
35 Dynamic type
37 Casting
41 Interfaces
47 Methods
52 Keywords
53 Recursion
57 Inheritance
58 Generics
62 Reflection
65 LINQ Queries
66 LINQ to XML
68 XmlDocument
69 XDocument
79 Diagnostics
80 Overflow
86 Properties
89 Events
93 Structs
94 Attributes
95 Delegates
97 Networking
102 Action Filters
103 Polymorphism
104 Immutability
105 Indexer
107 Stream
108 Timers
109 Stopwatches
110 Threading
112 Async Await
114 BackgroundWorker
117 Lock Statement
118 Yield Keyword
121 Func delegates
124 ICloneable
125 IComparable
127 Using SQLite
128 Caching
129 Code Contracts
136 Pointers
144 Hash Functions
146 Cryptography
148 C# Script
149 Runtime Compile
150 Interoperability
156 Contributors