Equals and GetHashCode:
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 thatEqualsreturns true), thenGetHashCodemust return the same value for each of them. - Large range: If two objects are not equal (
Equalssays 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
1
Literals
5
Equals and GetHashCode
17
Regex
18
DateTime
19
Arrays
21
Enum
22
Tuples
24
GUID
25
BigInteger
27
Looping
28
Iterators
29
IEnumerable
34
Dynamic type
36
Casting
40
Interfaces
46
Methods
51
Keywords
52
Recursion
56
Inheritance
57
Generics
61
Reflection
64
LINQ Queries
65
LINQ to XML
67
XmlDocument
68
XDocument
78
Diagnostics
79
Overflow
85
Properties
88
Events
92
Structs
93
Attributes
94
Delegates
96
Networking
101
Action Filters
102
Polymorphism
103
Immutability
104
Indexer
106
Stream
107
Timers
108
Stopwatches
109
Threading
111
Async Await
113
BackgroundWorker
116
Lock Statement
117
Yield Keyword
120
Func delegates
123
ICloneable
124
IComparable
126
Using SQLite
127
Caching
128
Code Contracts
135
Pointers
143
Hash Functions
145
Cryptography
147
C# Script
148
Runtime Compile
149
Interoperability
155
Contributors