dotnet/roslyn

Avoid checking HasValue in nullable comparison to non-default constants

Ouverte

#52 629 ouverte le 14 avr. 2021

 (3 commentaires) (2 réactions) (0 personne assignée)C# (4 257 forks)batch import
Area-CompilersCode Gen Qualityhelp wanted

Métriques du dépôt

Stars
 (20 414 étoiles)
Métriques de merge PR
 (Merge moyen 6j 17h) (256 PRs mergées en 30 j)

Description

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

Guide contributeur