Information Technology Reference
In-Depth Information
GetHashCode()). ValueType.GetHashCode() works only if the first field in
your
struct
is read-only. ValueType.GetHashCode() generates an effi-
cient hash code only when the first field in your
struct
contains values
across a meaningful subset of its inputs.
If you're going to build a better hash code, you need to place some constraints
on your type. Ideally, you'd create an immutable value type. The rules for
a working GetHashCode() are simpler for immutable value types than
they are for unconstrained types. Examine the three rules again, this time
in the context of building a working implementation of GetHashCode().
First, if two objects are equal, as defined by operator==(), they must return
the same hash value. Any property or data value used to generate the hash
code must also participate in the equality test for the type. Obviously, this
means that the same properties used for equality are used for hash code
generation. It's possible to have properties participate in equality that are
not used in the hash code computation. The default behavior for
System.ValueType does just that, but it often means that rule 3 usually gets
violated. The same data elements should participate in both computations.
The second rule is that the return value of GetHashCode() must be an
instance invariant. Imagine that you defined a reference type, Customer:
public class
Customer
{
private string
name;
private decimal
revenue;
public
Customer(
string
name)
{
this
.name = name;
}
public string
Name
{
get
{
return
name; }
set
{ name =
value
; }
}
public override int
GetHashCode()
{