Operator Overloading with Interface-Based Programming in C#

Zach Burlingame picture Zach Burlingame · Apr 8, 2009 · Viewed 17k times · Source

Background

I am using interface-based programming on a current project and have run into a problem when overloading operators (specifically the Equality and Inequality operators).


Assumptions

  • I'm using C# 3.0, .NET 3.5 and Visual Studio 2008

UPDATE - The Following Assumption was False!

  • Requiring all comparisons to use Equals rather than operator== is not a viable solution, especially when passing your types to libraries (such as Collections).

The reason I was concerned about requiring Equals to be used rather than operator== is that I could not find anywhere in the .NET guidelines that it stated it would use Equals rather than operator== or even suggest it. However, after re-reading Guidelines for Overriding Equals and Operator== I have found this:

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

and this Equatable Interface

The IEquatable interface is used by generic collection objects such as Dictionary, List, and LinkedList when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection.


Contraints

  • Any solution must not require casting the objects from their interfaces to their concrete types.

Problem

  • When ever both sides of the operator== are an interface, no operator== overload method signature from the underlying concrete types will match and thus the default Object operator== method will be called.
  • When overloading an operator on a class, at least one of the parameters of the binary operator must be the containing type, otherwise a compiler error is generated (Error BC33021 http://msdn.microsoft.com/en-us/library/watt39ff.aspx)
  • It's not possible to specify implementation on an interface

See Code and Output below demonstrating the issue.


Question

How do you provide proper operator overloads for your classes when using interface-base programming?


References

== Operator (C# Reference)

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.


See Also


Code

using System;

namespace OperatorOverloadsWithInterfaces
{
    public interface IAddress : IEquatable<IAddress>
    {
        string StreetName { get; set; }
        string City { get; set; }
        string State { get; set; }
    }

    public class Address : IAddress
    {
        private string _streetName;
        private string _city;
        private string _state;

        public Address(string city, string state, string streetName)
        {
            City = city;
            State = state;
            StreetName = streetName;
        }

        #region IAddress Members

        public virtual string StreetName
        {
            get { return _streetName; }
            set { _streetName = value; }
        }

        public virtual string City
        {
            get { return _city; }
            set { _city = value; }
        }

        public virtual string State
        {
            get { return _state; }
            set { _state = value; }
        }

        public static bool operator ==(Address lhs, Address rhs)
        {
            Console.WriteLine("Address operator== overload called.");
            // If both sides of the argument are the same instance or null, they are equal
            if (Object.ReferenceEquals(lhs, rhs))
            {
                return true;
            }

            return lhs.Equals(rhs);
        }

        public static bool operator !=(Address lhs, Address rhs)
        {
            return !(lhs == rhs);
        }

        public override bool Equals(object obj)
        {
            // Use 'as' rather than a cast to get a null rather an exception
            // if the object isn't convertible
            Address address = obj as Address;
            return this.Equals(address);
        }

        public override int GetHashCode()
        {
            string composite = StreetName + City + State;
            return composite.GetHashCode();
        }

        #endregion

        #region IEquatable<IAddress> Members

        public virtual bool Equals(IAddress other)
        {
            // Per MSDN documentation, x.Equals(null) should return false
            if ((object)other == null)
            {
                return false;
            }

            return ((this.City == other.City)
                && (this.State == other.State)
                && (this.StreetName == other.StreetName));
        }

        #endregion
    }

    public class Program
    {
        static void Main(string[] args)
        {
            IAddress address1 = new Address("seattle", "washington", "Awesome St");
            IAddress address2 = new Address("seattle", "washington", "Awesome St");

            functionThatComparesAddresses(address1, address2);

            Console.Read();
        }

        public static void functionThatComparesAddresses(IAddress address1, IAddress address2)
        {
            if (address1 == address2)
            {
                Console.WriteLine("Equal with the interfaces.");
            }

            if ((Address)address1 == address2)
            {
                Console.WriteLine("Equal with Left-hand side cast.");
            }

            if (address1 == (Address)address2)
            {
                Console.WriteLine("Equal with Right-hand side cast.");
            }

            if ((Address)address1 == (Address)address2)
            {
                Console.WriteLine("Equal with both sides cast.");
            }
        }
    }
}

Output

Address operator== overload called
Equal with both sides cast.

Answer

John Feminella picture John Feminella · Apr 8, 2009

Short answer: I think your second assumption may be flawed. Equals() is the right way to check for semantic equality of two objects, not operator ==.


Long answer: Overload resolution for operators is performed at compile time, not run time.

Unless the compiler can definitively know the types of the objects it's applying an operator to, it won't compile. Since the compiler cannot be sure that an IAddress is going to be something that has an override for == defined, it falls back to the default operator == implementation of System.Object.

To see this more clearly, try defining an operator + for Address and adding two IAddress instances. Unless you explicitly cast to Address, it will fail to compile. Why? Because the compiler can't tell that a particular IAddress is an Address, and there is no default operator + implementation to fall back to in System.Object.


Part of your frustration probably stems from the fact that Object implements an operator ==, and everything is an Object, so the compiler can successfully resolve operations like a == b for all types. When you overrode ==, you expected to see the same behavior but didn't, and that's because the best match the compiler can find is the original Object implementation.

Requiring all comparisons to use Equals rather than operator== is not a viable solution, especially when passing your types to libraries (such as Collections).

In my view, this is precisely what you should be doing. Equals() is the right way to check for semantic equality of two objects. Sometimes semantic equality is just reference equality, in which case you won't need to change anything. In other cases, as in your example, you'll override Equals when you need a stronger equality contract than reference equality. For example, you may want to consider two Persons equal if they have the same Social Security number, or two Vehicles equal if they have the same VIN.

But Equals() and operator == are not the same thing. Whenever you need to override operator ==, you should override Equals(), but almost never the other way around. operator == is more of a syntactical convenience. Some CLR languages (e.g. Visual Basic.NET) don't even permit you to override the equality operator.