I have some classes that override Equals
and GetHashCode
, but every now and then I need to compare by reference. So I have written a ReferenceEqualityComparer
like here: https://stackoverflow.com/a/35520207/5333340
Note that ReferenceEqualityComparer
implements IEqualityComparer<object>
.
Due to its contravariance I am not limited to collections of object
s, i.e. I can write
ISet<MyClass> setOfMyClass = new HashSet<MyClass>(ReferenceEqualityComparer.Default);
. But it seems that in some situations, the contravariance will not help: I'd like to use my ReferenceEqualityComparer
inside the method
Enumerable.ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
like so (just a small technical example, I know there is no point using ReferenceEqualityComparer
here):
var foo = new List<string> {"hello", "world", "to", "everyone"}
Dictionary<string, int> dict = foo.ToDictionary(x => x, x => x.Length, ReferenceEqualityComparer.Default);
Unfortunately, this does not work. Since the ReferenceEqualityComparer
implements IEqualityComparer<object>
, the resulting dictionary will be of type Dictionary<object, int>
(that's what Visual Studio tells me). So if I understand correctly, in order to get Dictionary<string, int>
, ReferenceEqualityComparer
would need to implement IEqualityComparer<string>
.
So how do I make ReferenceEqualityComparer
type-agnostic, i.e. make it implement IEqualityComparer<T>
for all possible types T
?
Or am I mixing something up and there is another way? I'm not so much interested in theoretical concepts, I just want some way of using a non-generic class (here: ReferenceEqualityComparer
) in a context where a generic class is expected.