Search code examples
c#compareto

Comapring two object does not invoke CompareTo method


My class is implementing IComparable interface as follows.

public class MyClass : IComparable<MyClass>
    {
        public SomeEnum?      Field1            { get; set; }
        public int?           Field2            { get; set; }

        public int CompareTo(MyClass other)
        {
            if (this.Field1 == other.Field1 && this.Field2 == other.Field2)
                return 0;
            else
                return 1;
        }
    }

Somewhere else in the code I am comparing two instance of this class as follows

if ( MyClassInstance1 != MyClassInstance2 )

At this point, I don't see CompareTo invoked. Any ideas what I am doing wrong here?


Solution

  • CompareTo() is a regular method, and can be called like any other regular method.

    It sounds like you actually want to overload the == and != operators (and override Equals() and GetHashCode()).