संपादित करें

इसके माध्यम से साझा किया गया


CA2264: Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'

Property Value
Rule ID CA2264
Title Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As warning

Cause

When a value that's known to never be null is passed to ArgumentNullException.ThrowIfNull(), an exception is never thrown, making the statement a no-op.

Rule description

ArgumentNullException.ThrowIfNull throws when the passed argument is null. Certain constructs like non-nullable structs (except for Nullable<T>), type parameters known to be non-nullable structs, 'nameof()' expressions, and 'new' expressions are known to never be null, so ArgumentNullException.ThrowIfNull will never throw.

In the case of a struct, since ArgumentNullException.ThrowIfNull accepts an object?, the struct is boxed, which causes an additional performance penalty.

How to fix violations

Remove the ArgumentNullException.ThrowIfNull call.

Example

The following code snippet shows a violation of CA2264:

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

The following code snippet fixes the violation:

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

When to suppress warnings

It's always safe to suppress this warning.

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 CA2264
// The code that's violating the rule is on this line.
#pragma warning restore CA2264

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

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

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