Consider the following objects:
class Route
{
public int Origin { get; set; }
public int Destination { get; set; }
}
Route implements equality operators.
class Routing
{
public List<Route> Paths { get; set; }
}
I used the code below to implement GetHashCode method for the Routing object and it seems to work but I wonder if that's the right way to do it? I rely on equality checks and as I'm uncertain I thought I'll ask you guys. Can I just sum the hash codes or do I need to do more magic in order to guarantee the desired effect?
public override int GetHashCode() =>
{
return (Paths != null
? (Paths.Select(p => p.GetHashCode())
.Sum())
: 0);
}
I checked several GetHashCode()
questions here as well as MSDN and Eric Lippert's article on this topic but couldn't find what I'm looking for.
GetHashCode
of the Collection itself? – ZoophilousGetHashCode
on theList<Route>
, it will not consider the contents of the list. It only guarantees to give the same hash code if the twoList<>
references are really pointing two one single list object (only one instance). – DiapophysisGetHashCode
. The implementation from the base classSystem.Object
does that already! But we will have to ask Joanna. – Diapophysis