Effective C#
Item 10 and 11
Understand the Pitfalls of GetHashCode
Item 10
Where to use?
• Define the hash value for keys in a hash-based collection– Hashtable– Dictionary
Three rules
• If two objects are equal (as defined by operator==), they must generate the same hash value
• For any object A, A.GetHashCode() must be an instance invariant
• The hash function should generate a random distribution among all integers for all inputs
Issues with Object.GetHashCode()
• Rule 1: Pass• Rule 2: Pass• Rule 3: Failed
ValueType.operator==() compares the first field in the struct
The following code snippet always returns true
Check 3 rules again
• Rule 1: Pass *• Rule 2: Pass *• Rule 3: Pass *
Modify previous code
Review Rule 1
• if two objects are equal, as defined by operator==(), they must return the same hash value
• => The same data elements should participate in both computations
Review Rule 2
• the return value of GetHashCode() must be an instance invariant
Hash is changed by data member
Improved by immutability of the properties
Review Rule 3
• GetHashCode() should generate a random distribution among all integers for all inputs– A common and successful algorithm is to XOR all
the return values from GetHashCode() on all fields in a type
– exclude mutable fields from the calculations.
Prefer foreach Loops
Item 11
Loops
BEST
WORST
Loop3: one bounds check for the price of two
foreach always generates the best code (1/2)
foreach always generates the best code (2/2)
Automatically casts each operand
Any hand-coded for loops are broken
Example
Resource management
Example
Benefits
• generates the right code for upper and lower bounds in arrays
• iterates multidimensional arrays• coerces the operands into the proper type• generates the most efficient looping
constructs
Weak points
• Can’t modify enumeration member
• Can’t delete member in the conllection
Top Related