Skip to content

Remove [DisallowNull] from EqualityComparer.GetHashCode #30998

@jnm2

Description

@jnm2

Visual Studio 16.3.1 generates code like this for GetHashCode specifically because this way the null check is handled. EqualityComparer.GetHashCode is well-known to return 0 if you pass null:

struct Foo
{
    public string? Bar { get; }

    public override int GetHashCode()
    {
        // CS8604 Possible null reference argument for parameter 'obj' in
        // 'int EqualityComparer<string?>.GetHashCode(string? obj)'.      ↓
        return 1739646154 + EqualityComparer<string?>.Default.GetHashCode(Bar);
    }
}

Rather than generating a ! to go along with it, could [DisallowNull] be removed from EqualityComparer<>.GetHashCode as a kind of contravariance, even though IEqualityComparer<>.GetHashCode has it? It would reflect the true behavior of the EqualityComparer<> class.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions