I want an IEqualityComparer<Type>
that returns true if and only if two generic types are the same ignoring generic parameters. So comparer.Equals(typeof(List<A>), typeof(List<B>))
should return true
.
I am doing a comparison by Name
:
public class GenericTypeEqualityComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y)
{
return x.Name == y.Name;
}
public int GetHashCode(Type obj)
{
return obj.Name.GetHashCode();
}
}
There are some false positive cases (namespace issues, etc.). I don't know what else to do.
Here is a check that takes the generic into account. It would throw a NRE if x or y were null though so if you want a more robust check add a null check too.
public bool Equals(Type x, Type y)
{
var a = x.IsGenericType ? x.GetGenericTypeDefinition() : x;
var b = y.IsGenericType ? y.GetGenericTypeDefinition() : y;
return a == b;
}