Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 166515
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T12:06:41+00:00 2026-05-11T12:06:41+00:00

Background I am using interface-based programming on a current project and have run into

  • 0

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. 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T12:06:41+00:00Added an answer on May 11, 2026 at 12:06 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 91k
  • Answers 91k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer When you save the page it will save the original… May 11, 2026 at 6:17 pm
  • Editorial Team
    Editorial Team added an answer Set the expires header in your web server to some… May 11, 2026 at 6:17 pm
  • Editorial Team
    Editorial Team added an answer This will probably work: def setVenueImage(img): img = images.Image(img.read()) x,… May 11, 2026 at 6:17 pm

Related Questions

I have been researching around trying to find the best way to begin developing
I am using a tab bar (UITabBarController) on my app and I wish to
Background: I have a big solution where hundreds of functions take strongly typed collections
Background: I am using ASP.NET 2.0 (with C#) and the code below is embedded

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.