Answer the question
In order to leave comments, you need to log in
Is it legal to return the ordinal number of an object in GetHashCode()?
Good day. There is this code:
namespace Stardust.Core.World
{
public class SpaceObject
{
public SpaceObject()
{
LastLeasedID++;
ID = LastLeasedID;
}
/// <summary>
/// Уникальный идентификатор этого объекта. Не может быть изменен после создания.
/// </summary>
public readonly Int32 ID;
public override Boolean Equals(Object obj)
{
var o = obj as SpaceObject;
if (o != null)
return this.ID == o.ID;
return false;
}
public Boolean Equals(SpaceObject other)
{
return other != null && this.ID == other.ID;
}
public override Int32 GetHashCode()
{
return ID;
}
public static Int32 LastLeasedID { get; private set; }
}
}
Answer the question
In order to leave comments, you need to log in
GetHashCode
The and
methods Equals
must be overridden if you want two different instances of the same class to be considered the same . In your case, the instance will only be equal to itself, because they Id
will always be unique. It turns out that you have reinvented the comparison semantics by reference, which already works by default, if not overridden at GetHashCode
all Equals
.
Another problem will arise if you use this code in a multi-threaded environment - without synchronization of access to, LastLeasedID
sooner or later you will get duplicates.
Universal hash code override rule by Joshua Bloch
Store some constant nonzero value, say 17, in an int variable called result.
Compute an int hashcode c for each field f that defines equals:
Using just the id is fine, but it needs to be multiplied by some number.
You are definitely reinventing the wheel. Almost any IDE has a function to automatically generate these methods with the ability to select the fields that will be taken into account.
As for this implementation, there is a similar example in the documentation
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question