Verification GetHashCode and Equals

Posted by nettguy on Stack Overflow See other posts from Stack Overflow or by nettguy
Published on 2010-03-29T08:25:35Z Indexed on 2010/03/29 8:33 UTC
Read the original article Hit count: 443

Filed under:
|
|

Does the following code show the correct implementation of overriding GetHashCode ?

    public class Person
    {
       public string fName{get;set;}
       public string lName { get; set; }
       public int age { get; set; }  

        public override bool Equals(object obj)
        {
            Person p = obj as Person;
            if (p == null) return false;

            return
                (
                   p.GetType()==this.GetType() && p.fName==this.fName
                   &&p.lName==this.lName && p.age==this.age
                );


        }

//I took the below code from Marc Gravell's post,I am not sure
  whether i have implemented it properly
        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 13;
                hash = (hash * 7) + fName.GetHashCode();
                hash = (hash * 7) + lName.GetHashCode();
                hash = (hash * 7) + age.GetHashCode();
                return hash;
            }
        }

}

© Stack Overflow or respective owner

Related posts about c#

Related posts about overriding