0

Is there any way to get to the double "==" operator for a generic parameter? Note that .Equals does not work correctly in all cases.

Given:

bool MyMethod<T>(T left, T right)
{
   return EqualityComparer.Default.Equals(left,right);
}

Then:

double a = double.NaN;
double b = double.NaN;
a == b; //returns false
MyMethod(a,b); //returns true

I'd like to get to the actual "==" operator for all types of T. Is that possible?

I have read Can't operator == be applied to generic types in C#? and it does not address my situation because the best answer suggests using EqualityComparer.Default but that does not return the mathematically correct value when comparing two double.NaN values.

PatrickV
  • 2,057
  • 23
  • 30
  • 1
    `EqualityComparer.Default.Equals(left, right)`? You can't get the `==` operator because it doesn't exist for every type, a struct does not have to have one – Charlieface Mar 23 '21 at 21:00
  • 1
    See https://learn.microsoft.com/en-us/dotnet/api/system.double.equals?view=net-5.0 which explains that (but not why) `==` and `.Equals` aren't the same when it comes to `double.NaN`. – Ian Mercer Mar 23 '21 at 21:03
  • 1
    See also https://stackoverflow.com/questions/11113259/how-to-call-custom-operator-with-reflection which may be what you are looking for. You would need to use reflection to get the operator method to call. – Ian Mercer Mar 23 '21 at 21:05
  • 1
    Can you check this possible duplicate https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c – Sergey K Mar 23 '21 at 21:08
  • I'd read that. Skeet's answer seems the best, but EqualityComparer.Default returns true for two double.NaN values, not false like the == operator. So there's some fine details that question doesn't seem to address for my situation. Unless I missed something. – PatrickV Mar 23 '21 at 21:26

0 Answers0