dotnet/roslyn

Bad diagnostic for OrElse operator with nullable types

Open

#14 098 ouverte le 27 sept. 2016

Voir sur GitHub
 (3 commentaires) (0 réactions) (0 assignés)C# (4 257 forks)batch import
Area-CompilersBugCommunityConcept-Diagnostic Clarityhelp wanted

Métriques du dépôt

Stars
 (20 414 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (256 PRs mergées en 30 j)

Description

Example 1: nullable -> nullable

public static void Main(string[] args)
{
    TrueFalseStruct? c = new TrueFalseStruct();
    TrueFalseStruct? c2 = new TrueFalseStruct();
    var x = c || c2; // Error
    var y = c | c2; // Works
}

public struct TrueFalseStruct
{
    public static bool operator true(TrueFalseStruct boolClass) => false;
    public static bool operator false(TrueFalseStruct boolClass) => true;

    public static TrueFalseStruct? operator |(TrueFalseStruct? b1, TrueFalseStruct? b2) => new TrueFalseStruct();
}

Example 2: nullable -> non-nullable

public static void Main(string[] args)
{
    TrueFalseStruct? c = new TrueFalseStruct();
    var x = c || new TrueFalseStruct(); // Error
    var y = c | new TrueFalseStruct(); // Works
}

public struct TrueFalseStruct
{
    public static bool operator true(TrueFalseStruct boolClass) => false;
    public static bool operator false(TrueFalseStruct boolClass) => true;

    public static TrueFalseStruct operator |(TrueFalseStruct b1, TrueFalseStruct b2) => new TrueFalseStruct();
}

Problem

Error CS0218: In order for 'Namespace.TrueFalseStruct.operator |(Namespace.TrueFalseStruct, Namespace.TrueFalseStruct)' to be applicable as a short circuit operator, its declaring type 'Namespace.TrueFalseStruct' must define operator true and operator false.

Interestingly, replacing || with | compiles without any errors.

This error is wrong: TrueFalseStruct does in fact have these operators defined. I'm not sure if this is a bug in the type checker not allowing nullables, or just a bad diagnostic that the checker produces.

Guide contributeur