0

Suppose I have some IEqualityComparer<in T> implemented. I have some constraints in my framework and I am using the microsoft MVVM framework. So the moment I am calling the functionality, my T will be of type object, while I know that the underlying values are in this case double.

I receive an InvalidCastException:

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'DoubleEqualityComparer' to type 'System.Collections.Generic.IEqualityComparer`1[System.Object]'

I tried the same with a class Foo, but also no luck with the cast. I expected that because T is only in, that it would resolve well. What am I missing?

using System.Collections.Generic;

public class DoubleEqualityComparer : IEqualityComparer<double>
{
    public bool Equals(double a, double b)
    {
        return true;
    }
    
    public int GetHashCode(double a)
    {
        return a.GetHashCode();
    }
}

public class Program
{
    public static void Main()
    {
        var comparer = new DoubleEqualityComparer();
        var objectComparer = (IEqualityComparer<object>)comparer;
    }
}
Marnix
  • 6,384
  • 4
  • 43
  • 78
  • 1
    If you could do that, it would mean that you'd have a reference to `comparer`, the `objectComparer` through which you could pass anything as an argument, not just `double` values. This would break `comparer`, because it can only handle doubles. – Leandro Jun 15 '22 at 14:33
  • What would `DoubleEqualityComparer.GetHashCode(new object())` do if that was allowed? That could get called if you allowed that cast, just by doing `objectComparer.GetHashCode(new object());`. – Matthew Watson Jun 15 '22 at 14:35
  • @MakePeaceGreatAgain that makes sense. I will reconsider my implementation. I guess I need some kind ObjectEqualityComparer that does dynamic type checking, because I really want to do double epsilon comparison if the values are doubles. – Marnix Jun 15 '22 at 14:38
  • @Marnix You could implement the non-generic `IEqualityComparer`. Here's an example on DotNetFiddle: https://dotnetfiddle.net/1rkFPZ – Matthew Watson Jun 15 '22 at 15:07
  • 1
    Thanks for the tip. Except that microsoft MVVM requires `IEqualityComparer`. So I am going to find another workaround. Probably implement `IEqualityComparer` so that covariance does work. – Marnix Jun 15 '22 at 15:08

0 Answers0