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?