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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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:


1
2
3
4
5
6
7
8
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);