Hello,
i have some questions about the HashCode of immutable types.
- May i "pre"-generate the HashCode of an immutable type in the constructor or are there any reason not do that?
- Should i always generate the Hashcode again, when the method GetHashCode() is called?
Here´s a sample class :
public class Id {
private readonly object _value;
private readonly int _hash = -1;
public Id( object value ) {
_value = value;
_hash = ( int ) ( 7 * value.GetType().GetHashCode() + 7 + 7 * _value.GetHashCode() );
}
public object Value {
get {
return _value;
}
}
public override int GetHashCode() {
return _hash;
}
public override bool Equals( object obj ) {
Id other = obj as Id;
if ( other == null ) {
return false;
}
return this.GetHashCode() == other.GetHashCode();
}
}