No.
In C#/.Net hash code is not involved into default implementation of ==
, !=
or Equals
. If object is reference type and it is moved by GC there is nothing outside of this object that will impact default comparisons.
Edit: unrelated details about comparison below.
==
and Equals
are not related to each other (except by convention).
In C# you have operator == that class/struct can overload. Default behavior is to compare references for reference types, value compare for system value types and for custom 'struct' there is no ==
operator auto-generated. Note that the other comparison Equals
is not involved into default definition of operator ==
.
For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object.
You can also provide your custom Object.Equals
for class. Good practice for classes the redefine ==
or Equals
is to redefine all comparison related methods to work consistently (==
, !=
, Equals(object other)
, and GetHashCode
; possibly Equals(myType other)
).
The only usage of GetHashCode
in .Net is hash-based collections like Dictionary
, HashSet
. Check GetHashCode Guidelines in C#
Obvious sample of custom comparison is System.String
(string
) - it is reference type but behaves as regular value type in relation to comparison.
So back to the original sample:
- if
IntegerPlus
isstruct
without custom "=="/Equals
: there is no==
automatically created (new IntegerPlus(42) == new IntegerPluss(42)
- syntax error). You get value comparison for all fields forEquals
(automatically provided). - if
IntegerPlus
isclass
that does not provide customoperator ==
orEquals
you get reference comparison andnew IntegerPlus(42) != new IntegerPluss(42)
and same forEquals
- if
IntegerPlus
provide only one of==
,!=
,Equals
than behavior will be as defined by custom implementation (likely unexplainable by external observer) - if
IntegerPlus
is either value or reference type and provides consistent set of all 4 comparison related methods you can get value comparison behavior