Search code examples
c#inheritanceequalsgethashcode

Overriding Equals and GetHashCode - default implementation in derived class


I'm a little confused about the default behaviour of Equals and GetHashCode in C#. Say I have two classes, one deriving from the other:

public abstract class Question
    {
        public string QuestionText
        {
            get;
            set;
        }

        public override bool Equals(object obj)
        {
            if (obj is Question)
            {
                Question q = (Question)obj;
                return this.QuestionText.Equals(q.QuestionText);
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            int hash = 13; 
            hash = (hash * 7) + this.QuestionText.GetHashCode(); 
            return hash; 
        }
 }

public class QuestionTrueFalse : Question
    {
        public bool CorrectAnswer
        {
            get;
            set;
        }

        public override bool Equals(object obj)
        {
            return base.Equals(q);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode(); 
        }
    } 

The derived class doesn't affect whether one item equals another, I still want that to be based simply upon the QuestionText property.

Do I need to override Equals and GetHashCode to reference the base implementation, as I have done here, or is that the default behaviour?


Solution

  • The base class behavior is inherited by the inheriting classes. You don't need to explicitly override Equals and GetHashCode unless you want to change their behavior.