dotnet/roslyn

Bad diagnostic for OrElse operator with nullable types

Open

#14,098 创建于 2016年9月27日

在 GitHub 查看
 (3 评论) (0 反应) (0 负责人)C# (4,257 fork)batch import
Area-CompilersBugCommunityConcept-Diagnostic Clarityhelp wanted

仓库指标

Star
 (20,414 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 256 个 PR)

描述

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.

贡献者指南