-1

I asked this question recently: When would == be overridden in a different way to .equals?. I was referred to this article: https://ericlippert.com/2013/10/07/math-from-scratch-part-six-comparisons/

I don't fully understand the reference to static method calls (== and !=) and dynamic method calls (.Equals()). Please see the code below:

public class A
{
    private string Field1;
    private string Field2;

    public A(string field1, string field2)
    {
        Field1 = field1;
        Field2 = field2;
    }

    public static bool operator ==(A a1, A a2)
    {
        throw new NotImplementedException();
    }

    public static bool operator !=(A a1, A a2b)
    {
        throw new NotImplementedException();
    }

    public override int GetHashCode()
    {
        throw new NotImplementedException();
    }

    public override bool Equals(object obj)
    {
        throw new NotImplementedException();
    }
}

public class B : A
{
    private string Field3;
    private string Field4;

    public B(string field1, string field2, string field3, string field4)
        : base(field1, field2)
    {
        Field3 = field3;
        Field4 = field4;
    }

    public static bool operator ==(B a1, B a2)
    {
        throw new NotImplementedException();
    }

    public static bool operator !=(B a1, B a2b)
    {
        throw new NotImplementedException();
    }

    public override int GetHashCode()
    {
        throw new NotImplementedException();
    }

    public override bool Equals(object obj)
    {
        throw new NotImplementedException();
    }
}

and the test below:

A a1 = new B("hello","hello","hello","hello");
A a2 = new B("hello", "hello", "hello", "hello");
var test1 = a1.Equals(a2);
var test2 = a1 == a2;

I do not understand the reason it is implemented this way? I have spent the last hour this evening Googling this, however I am still not clear and hence the reason for the question. Why is .Equals() dispatched dynamically and == dispatched statically?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
w0051977
  • 15,099
  • 32
  • 152
  • 329

1 Answers1

7

.Equals() is a virtual instance method, which is subject to normal overriding rules / polymorphism.

== is syntactic sugar for the static .op_Equality() method, which is a normal static method call with two parameters and therefore does no dynamic dispatch at all.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • What do you mean by "syntactic sugar"? I realise it is also stated like this in the article I posted. +1. – w0051977 Feb 14 '18 at 21:05
  • Thanks. I should of seen that when I searched. Sorry. Also what do you mean by: .op_Equals() – w0051977 Feb 14 '18 at 21:08
  • 2
    @w0051977: Oops; that should be `op_Equality`. Overloaded operators are syntactic sugar for static methods with names like that. You can see this in stack traces, decompilers, or Reflection. – SLaks Feb 14 '18 at 21:11