Search code examples
c#stringcomparisonoperator-overloadinggethashcode

Overloading == operator for class containing only string attributes


What would be the best (most elegant or performing) way of overloading the equality operator on a class containing only string attributes?

Example:

class MagicClass
{
    public string FirstAttribute { get; set; }
    public string SecondAttribute { get; set; }
    public string ThirdAttribute { get; set; }
    public string FourthAttribute { get; set; }
    public string FifthAttribute { get; set; }
}

I know how to overload the operator itself, however, I am wondering about the following points:

  1. Is there a way to elegantly compare such two objects (e.g. without having to write an if statement containing mutual comparisons of all the attributes
  2. What would be a good implementation of the GetHashCode() method in such case

Solution

  • How about something like this, Just create array of all properties and a loop.

    internal class MagicClass
    {
        public string FirstAttribute { get; set; }
        public string SecondAttribute { get; set; }
        public string ThirdAttribute { get; set; }
        public string FourthAttribute { get; set; }
        public string FifthAttribute { get; set; }
    
        private string[] AllProperties//Array of all properties
        {
            get
            {
                return new[]
                {
                    FirstAttribute,
                    SecondAttribute,
                    ThirdAttribute,
                    FourthAttribute,
                    FifthAttribute
                };
            }
        }
    
        protected bool Equals(MagicClass other)
        {
            var thisProps = this.AllProperties;
            var otherProps = other.AllProperties;
    
            return thisProps.SequenceEqual(otherProps);
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((MagicClass) obj);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                var thisProps = this.AllProperties;
                int hashCode = 0;
                foreach (var prop in thisProps)
                {
                    hashCode = (hashCode * 397) ^ (prop != null ? prop.GetHashCode() : 0);
                }
                return hashCode;
            }
        }
    }
    

    Then you can call Equals method inside your operator overload. If you're lazy to create AllProperties array you can use Reflection but IMO reflection is overkill here.