dotnet/roslyn

class? constraint combines poorly with non-nullable interface constraint

Open

#49,571 opened on Nov 23, 2020

View on GitHub
 (8 comments) (0 reactions) (1 assignee)C# (4,257 forks)batch import
Area-CompilersBugFeature - Nullable Reference Typeshelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

Description

Version Used: dc6f316a5e4f8eb3a0d36ab356c5c12686db00a9

Steps to Reproduce:

#nullable enable
using System;
public class C {
    public void M<T>(T t) where T : class?, IEquatable<T> {
        t.ToString(); // no warning?
    }
}

Expected Behavior: Variable of type T has a maybe-null initial state

Actual Behavior: Variable has not-null initial state

Remarks: This may be fine and by-design, however the combination of these particular constraints seems to produce a contradictory/unintuitive result, so maybe there should be a warning to change class? to class, or to change IEquatable<T> to IEquatable<T>?.

We should report a warning under the following condition:

If the collection of interface, base class and the class constraints on a type parameter contain a single one which is "non-nullable" then we should warn if any of the others are "nullable".

Contributor guide