Example of Overloading the == Operator

Here’s a full example that shows how to overload the == operator for a reference type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class PersonHeight
{
    public int Feet { get; set; }
    public int Inches { get; set; }
 
    // Constructor goes here
 
    public override bool Equals(object obj)
    {
        return ((obj is PersonHeight) && ((PersonHeight)obj == this));
    }
 
    public override int GetHashCode()
    {
        return Feet.GetHashCode() ^ Inches.GetHashCode();
    }
 
    public static bool operator ==(PersonHeight ph1, PersonHeight ph2)
    {
        if (ReferenceEquals(ph1, ph2))
            return true;
 
        if (((object)ph1 == null) || ((object)ph2 == null))
            return false;
 
        return (ph1.Feet == ph2.Feet) && (ph1.Inches == ph2.Inches);
    }
 
    public static bool operator !=(PersonHeight ph1, PersonHeight ph2)
    {
        return !(ph1 == ph2);
    }
 
    // Also overload < and > operators
}
Test cases:


1
2
3
4
5
6
7
8
9
10
11
12
PersonHeight ph1 = new PersonHeight(5, 10);
PersonHeight ph2 = new PersonHeight(5, 10);
PersonHeight ph3 = null;
 
bool check = ph1.Equals(null);
check = ph1.Equals("NO!");
check = ph1.Equals(ph2);
check = PersonHeight.Equals(ph1, ph2);
 
check = (ph1 == null);
check = (ph3 == null);
check = (ph1 == ph2);