Skip to content

perf: use Nullable<T>.GetValueOrDefault() instead of Nullable<T>.Value #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 10, 2024

Conversation

nogic1008
Copy link
Contributor

Nullable<T>.Value always does null check as below.

If we know it's not null, we can avoid the extra if by using Nullable<T>.GetValueOrDefault() instead.

public struct Nullable<T> where T : struct
{
    private readonly bool hasValue;
    internal T value;

    public readonly T Value
    {
        get
        {
            if (!hasValue)
            {
                ThrowHelper.ThrowInvalidOperationException_InvalidOperation_NoValue();
            }
            return value;
        }
    }

    public readonly T GetValueOrDefault() => value;
}

Inspired by dotnet/coreclr#22297, .NET blog post

@neuecc
Copy link
Member

neuecc commented Dec 10, 2024

Thank you, I wasn't aware of that at all!
Thank you also for the blog reference, it's very helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants