dotnet/roslyn

Avoid checking HasValue in nullable comparison to non-default constants

オープン

#52,629 opened on 2021/04/14

 (3 件のコメント) (2 件のリアクション) (0 人の担当者)C# (4,257 件のフォーク)batch import
Area-CompilersCode Gen Qualityhelp wanted

Repository metrics

Stars
 (20,414 個のスター)
PR merge metrics
 (平均マージ 6d 17h) (30d で 256 merged PRs)

説明

@canton7 mentioned the following in https://github.com/dotnet/roslyn/issues/44109#issuecomment-664292439

It occurs to me that, provided one side of the == is a constant which has a non-default value, we can skip the & x.HasValue check altogether.

It feels like it would be a nice little win if, when comparing a System.Nullable<T> to a constant with a non-default value, we could avoid generating code to check HasValue. For example: SharpLab

void M(int? x)
{
    if (x == 42)
    {
        System.Console.Write(1);
    }
}

Could be lowered to:

void M(int? x)
{
    if (x.GetValueOrDefault() == 42)
    {
        System.Console.Write(1);
    }
}

Currently we generate:

void M(Nullable<int> x)
{
    Nullable<int> num = x;
    int num2 = 42;
    if ((num.GetValueOrDefault() == num2) & num.HasValue)
    {
        Console.Write(1);
    }
}

コントリビューターガイド