dotnet/roslyn

Avoid checking HasValue in nullable comparison to non-default constants

Open

#52,629 opened on Apr 14, 2021

View on GitHub
 (3 comments) (2 reactions) (0 assignees)C# (4,257 forks)batch import
Area-CompilersCode Gen Qualityhelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

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

Contributor guide