Checking equality of generic values.

suggest change

If 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents