Pregunta

public class MyClass
{
   public string x;
   public string y;
}

public class MyClassEqualityComparer : IEqualityComparer<MyClass>
{
     public int GetHashCode(MyClass myobj)
     {
         if(myObj == null)
         {
            return base.GetHashCode();
         }
         if (myObj.x != null && myObj.y != null)
         {
              return myObj.x.GetGashCode()^myObj.y.GetGashCode();
         }
     }
}

what should be the implementation if myObj.x or/and myObj.y are nulls

¿Fue útil?

Solución

The only requirement for a hash code is that two objects that are considered equal share the same hash code.

You can, for example, use 0 for null properties

public int GetHashCode(MyClass myobj)
{
     if(myObj == null)
     {
        return base.GetHashCode();
     }
     return (myObj.x != null ? myObj.x.GetGashCode() : 0) ^ (myObj.y != null ? myObj.y.GetGashCode() : 0)
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top