#409 – Example of Overloading the == Operator
September 12, 2011 Leave a comment
Here’s a full example that shows how to overload the == operator for a reference type.
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:
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);