Checking equality of generic values.
suggest changeIf a generic class or method needs to compare values of its type parameter, use the EqualityComparer<T>.Default property:
public void Foo<TBar>(TBar arg1, TBar arg2)
{
var comparer = EqualityComparer<TBar>.Default;
if (comparer.Equals(arg1, arg2))
{
...
}
}
This approach is better than calling Object.Equals(), because the default comparer checks whether TBar implements IEquatable<TBar> (interface) and, if it does, calls IEquatable<TBar>.Equals(TBar other). That avoids boxing value types.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents