dotnet/roslyn

Bad diagnostic for OrElse operator with nullable types

Open

#14.098 geöffnet am 27. Sept. 2016

Auf GitHub ansehen
 (3 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (4.257 Forks)batch import
Area-CompilersBugCommunityConcept-Diagnostic Clarityhelp wanted

Repository-Metriken

Stars
 (20.414 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (256 gemergte PRs in 30 T)

Beschreibung

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.

Contributor Guide