none
GetHashCode RRS feed

  • Question

  • Hello,

    I have a class containing 4 private attributes(2 int,1 String,1 enumered type) and 3 methods

    I want to implement the getHashCode Method.


    How can i proceed?

    Thanks in advance.
    Monday, July 7, 2008 8:39 AM

Answers

  • Just XOR the hash codes of the members that are used to test for equality:

        public class Test {
          private int ival, ival2;
          private string sval;
          public override int GetHashCode() {
            return ival.GetHashCode() ^ ival2.GetHashCode() ^ sval.GetHashCode();
          }
          public override bool Equals(object obj) {
            Test rhs = obj as Test;
            if (rhs == null) return base.Equals(obj);
            return ival == rhs.ival && ival2 == rhs.ival2 && sval == rhs.sval;
          }
        }


    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, July 14, 2008 1:19 AM
    Monday, July 7, 2008 12:29 PM
    Moderator