dotnet/roslyn

Bad diagnostic for OrElse operator with nullable types

Open

#14.098 aperta il 27 set 2016

Vedi su GitHub
 (3 commenti) (0 reazioni) (0 assegnatari)C# (4257 fork)batch import
Area-CompilersBugCommunityConcept-Diagnostic Clarityhelp wanted

Metriche repository

Star
 (20.414 star)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

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.

Guida contributor