#409 – Example of Overloading the == Operator

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);
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: