0
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

YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • 1
    `base.GetHashCode()` is the hash code *of the comparer*. Makes no sense. – usr Mar 11 '14 at 11:49
  • possible duplicate of [What is the best algorithm for an overridden System.Object.GetHashCode?](http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode) – GSerg Mar 16 '14 at 12:09

1 Answers1

1

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)
}
CodeCarvings
  • 224
  • 1
  • 3
  • I am looking for better solution than returning 0 .for that reson I don`t return 0 if myObj is null – YAKOVM Mar 11 '14 at 11:46
  • @Yakov there is no better solution. You have to assign an arbitrary value for the `null` case. Maybe use a randomly chosen constant. – usr Mar 11 '14 at 11:50
  • @usr - what do you think the correct thing to do if myObj == null : also return 0? – YAKOVM Mar 11 '14 at 11:53
  • What about "DBNull.Value.GetHashCode()" ? – CodeCarvings Mar 11 '14 at 11:55
  • @Yakov return `0` or a randomly chosen constant that you hard-code into the source code. – usr Mar 11 '14 at 11:56
  • @Yakov, you have to return an int number... You have 2^32 possibilities... just choose one. the ONLY important thing is that you ALWAYS use that number for a particular NULL field. – CodeCarvings Mar 11 '14 at 12:05