#410 – Overloading the == Operator for a Value Type

A user-defined struct automatically inherits an Equals method that performs a value equality check by comparing each field of the struct. The == operator, however, is not automatically defined.  If you want to use the == operator for instances of a struct, you need to overload the == operator.

    public struct PersonHeight
    {
        public int Feet { get; set; }
        public int Inches { get; set; }

        public PersonHeight(int feet, int inches) : this()
        {
            Feet = feet;
            Inches = inches;
        }

        public static bool operator ==(PersonHeight ph1, PersonHeight ph2)
        {
            return (ph1.Feet == ph2.Feet) && (ph1.Inches == ph2.Inches);
        }

        public static bool operator !=(PersonHeight ph1, PersonHeight ph2)
        {
            return !(ph1 == ph2);
        }
    }

Some test cases:

            PersonHeight ph1 = new PersonHeight(5, 10);
            PersonHeight ph2 = new PersonHeight(5, 10);

            // Returns true, default Equals method compares each field
            bool check = ph1.Equals(ph2);

            // == operator also now works - true
            check = (ph1 == ph2);