I want to write an equality comparer for Nullable structs. Lets say, DateTime?
.
So I come up with this code:
public class NullableEntityComparer<TEntity, TType> : IEqualityComparer<TEntity>
where TType : struct
where TEntity : Nullable<TType>
{
public bool Equals(TEntity x, TEntity y)
{
if(!x.HasValue && ! y.HasValue) return true;
if(x.HasValue && y.HasValue) return x.Value == y.Value;
return false;
}
public int GetHashCode(TEntity obj)
{
if (obj == null) throw new ArgumentNullException("obj");
if (obj.HasValue) return obj.Value.GetHashCode();
else return obj.GetHashCode();
}
}
The compiler doesn't like this and tells me:
'TType?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
This is a clear message, however Nullable<T>
is a class, and TType?
is just a shorthand for Nullable<TType>
. Or am I missing something?
Why does this not work? And is there a solution to have an IEqualityComparer<T>
use the T.HasValue
property?