Gotcha

I don’t have to implement/override Equals that often in my classes so I always have a hard time remembering some of the subtleties behind it. This problem isn’t new, but it has been a very long time since I have dealt with it. If you are trying to invoke the Equals method or the == operator from a Generic (Type T) context then you will run into problems. Therefore, how do you do this properly?

Solution

The default Equals method has an overload that takes two arguments which you would use in this case. The reason for this is because if you are comparing two objects of type T:

  1. If the left hand argument is null then a NullReferenceException will be raised.
  2. If you attempt to utilize the == operator then you will get false positives because it is not using your Type’s definition of the operator in a Generic context (unfortunate).

Credit

I needed help remembering this answer and I found it here:

https://www.c-sharpcorner.com/article/equality-operator-with-inheritance-and-generics-in-c-sharp/

This is the code snippet that made the light bulb turn back on for me which I got from the above article:

static void Equals<T>(T a, T b) where T  
{
    Console.WriteLine(object.Equals(a,b));
}

Leave a Reply

Your email address will not be published. Required fields are marked *