All rules
CA1871Performance Enabled by default: As information

Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'

Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'

Microsoft docs

Description

For improved performance, it's better to check the HasValue property and manually throw an exception than to pass a nullable struct to ArgumentNullException.ThrowIfNull.

Cause

When a nullable struct, for example, int? or Guid?, is passed to ArgumentNullException.ThrowIfNull, it's boxed to an object, causing a performance penalty.

How to fix violations

Check for null and throw the System.ArgumentNullException manually.

Example

static void Print(int? value)
{
    ArgumentNullException.ThrowIfNull(value);
    Console.WriteLine(value.Value);
}

static void Print(int? value)
{
    if (!value.HasValue)
    {
        throw new ArgumentNullException(nameof(value));
    }

    Console.WriteLine(value.Value);
}

When to suppress

It's safe to suppress this warning if performance isn't a concern.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0