Presentation is loading. Please wait.

Presentation is loading. Please wait.

Effective C# Item 10 and 11. Understand the Pitfalls of GetHashCode Item 10.

Similar presentations


Presentation on theme: "Effective C# Item 10 and 11. Understand the Pitfalls of GetHashCode Item 10."— Presentation transcript:

1 Effective C# Item 10 and 11

2 Understand the Pitfalls of GetHashCode Item 10

3 Where to use? Define the hash value for keys in a hash-based collection – Hashtable – Dictionary

4 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

5 Issues with Object.GetHashCode() Rule 1: Pass Rule 2: Pass Rule 3: Failed

6 ValueType.operator==() compares the first field in the struct The following code snippet always returns true

7 Check 3 rules again Rule 1: Pass * Rule 2: Pass * Rule 3: Pass *

8 Modify previous code

9 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

10 Review Rule 2 the return value of GetHashCode() must be an instance invariant

11 Hash is changed by data member

12 Improved by immutability of the properties

13 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.

14 Prefer foreach Loops Item 11

15 Loops BEST WORST

16 Loop3: one bounds check for the price of two

17 foreach always generates the best code (1/2)

18 foreach always generates the best code (2/2)

19 Automatically casts each operand Any hand-coded for loops are broken

20 Example

21 Resource management

22 Example

23 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

24 Weak points Can’t modify enumeration member Can’t delete member in the conllection


Download ppt "Effective C# Item 10 and 11. Understand the Pitfalls of GetHashCode Item 10."

Similar presentations


Ads by Google