Return m_X.GetHashCode Xor m_Y.GetHashCode Public Overrides Function GetHashCode() As Integer Return _X.GetHashCode() ^ _Y.GetHashCode() The easiest way to do this is to simply use an exclusive or on the hash codes of all the fields used for equality. The next step is to generate the hash codes. Implements System.IEquatable(Of PointClass).Equals Public Overloads Function Equals( ByVal other As PointClass) As Boolean Return ( this._X = other._X) & (this._Y = other._Y) If ( Object.ReferenceEquals(other, this)) If ( Object.ReferenceEquals(other, null)) We are comparing the private fields, but there is no reason we could not have used the properties instead. Since classes are always equal to themselves, there is a check for that before the potentially more expensive equality checks. This backdoor is the Object.ReferenceEquals function. Since we specifically don't want to use =, which we will be overriding, we have to turn to a backdoor. The former uses the Is operator, while the latter uses the = operator.Ĭ# lacks this distinction and uses the = operator for both. Visual Basic has an explicit distinction between reference equality and value equality. This is because of a difference between how C# and VB handle equality.
#VISUAL BASIC NOT EQUAL CODE#
You will note that we are not using idiomatic C# code when checking for nulls. By convention, all non-nulls are considered unequal to null. Return m_X = other.m_X AndAlso m_Y = other.m_Yįor classes, an extra check needs to be made for null values. Implements System.IEquatable( Of PointStruct).Equals VB Public Overloads Function Equals( ByVal other As PointStruct) As Boolean _ Return ( this._X = other._X) & ( this._Y = other._Y) The first method we implement is the type-safe Equals, which is used by the IEquatable interface. Since the class versions are nearly identical, or completely identical as in the case of VB, they will not be shown here. Public Sub New( ByVal x As Integer, ByVal y As Integer) But once fully initialized, there is no way to alter them directly. This is a bit of a misnomer, as they can be set in constructors. To help ensure that the fields stay immutable, they are marked as read-only. The most common symptom is not being able to find objects that were previously placed in the collection. If the hash code changes, the object will be in the wrong slot and the collection will not work correctly. For all of these, the hash code is used for searching and storage. Examples include Hashtable, Dictionary, HashSet, and KeyedCollection. This rule is vitally important when using anything that relies on hashing. This usually means that either all properties on the class are read-only or the class has a unique identifier like a database key.