Below is a simple test program that throws a StackOverflowException
when Equals
is called. I expected the generic Equals
that I got from object to call my IEquatable<MyClass>.Equals
, but it does not, it calls itself instead. Why? The parameter type seems ok. Why does it call the generic version in the first place? I am confused.
using System;
namespace consapp
{
class Program
{
static void Main(string[] args)
{
MyClass x0 = new MyClass("x0");
MyClass x1 = new MyClass("x");
Console.WriteLine(x1.Equals(x0));
}
}
internal class MyClass : IEquatable<MyClass>
{
public string Name { get; set; }
public MyClass(string s) { this.Name = s; }
public override bool Equals(object x) { return this.Equals(x as MyClass); }
public override int GetHashCode() { return this.Name.ToLowerInvariant().GetHashCode(); }
bool IEquatable<MyClass>.Equals(MyClass x) { return x != null && this.Name == x.Name; }
}
}