Can’t operator == be applied to generic types in C#?

As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null – and that comparison will always be false for non-nullable value types.

Instead of calling Equals, it’s better to use an IComparer<T> – and if you have no more information, EqualityComparer<T>.Default is a good choice:

public bool Compare<T>(T x, T y)
{
    return EqualityComparer<T>.Default.Equals(x, y);
}

Aside from anything else, this avoids boxing/casting.

Leave a Comment