It is ok (no negative consequences) only if GetHashCode
is unique for each possible value. To give an example, the GetHashCode
of a short
(a 16 bit value) is always unique (let's hope it so :-) ), so basing the Equals
to the GetHashCode
is ok.
Another example, for int
, the GetHashCode()
is the value of the integer, so we have that ((int)value).GetHashCode() == ((int)value)
. Note that this isn't true for example for short
(but still the hash codes of a short
are unique, simply they use a more complex formula)
Note that what what Patrick wrote is wrong, because that is true for the "user" of an object/class. You are the "writer" of the object/class, so you define the concept of equality and the concept of hash code. If you define that two objects are always equal, whatever their value is, then it's ok.
public override int GetHashCode() { return 1; }
public override bool Equals(object obj) { return true; }
The only important rules for Equals are:
Implementations are required to ensure that if the Equals method returns true for two objects x and y, then the value returned by the GetHashCode method for x must equal the value returned for y.
The Equals method is reflexive, symmetric, and transitive...
Clearly your Equals()
and GetHashCode()
are ok with this rules, so they are ok.
Just out of curiosity, there is at least an exception for the equality operator (==
) (normally you define the equality operator based on the Equals
method)
bool v1 = double.NaN.Equals(double.NaN); // true
bool v2 = double.NaN == double.NaN; // false
This because the NaN
value is defined in the IEEE 754 standard as being different from all the values, NaN
include. For practical reasons, the Equals
returns true
.