Skip to content

Avoid checking HasValue in nullable comparison to non-default constants #52629

@RikkiGibson

Description

@RikkiGibson

@canton7 mentioned the following in #44109 (comment)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated codehelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions