dotnet/roslyn

Avoid checking HasValue in nullable comparison to non-default constants

Aperta

#52.629 aperta il 14 apr 2021

 (3 commenti) (2 reazioni) (0 assegnatari)C# (4257 fork)batch import
Area-CompilersCode Gen Qualityhelp wanted

Metriche repository

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

Descrizione

@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);
    }
}

Guida contributor