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

Property Value
Rule ID CA1871
Title Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As information

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.

Rule 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.

How to fix violations

Check for null and throw the ArgumentNullException manually.

Example

The following code snippet shows a violation of CA1871:

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

The following code snippet fixes the violation:

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

    Console.WriteLine(value.Value);
}

When to suppress warnings

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

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1871
// The code that's violating the rule is on this line.
#pragma warning restore CA1871

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1871.severity = none

For more information, see How to suppress code analysis warnings.