Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
| Property | Value | 
|---|---|
| Rule ID | CA1510 | 
| Title | Use ArgumentNullException throw helper | 
| Category | Maintainability | 
| Fix is breaking or non-breaking | Non-Breaking | 
| Enabled by default in .NET 9 | As suggestion | 
Cause
Code checks whether an argument is null and then conditionally throws an ArgumentNullException.
Rule description
Argument checks have a substantial impact on code size and often dominate the code for small functions and property setters. These checks prevent inlining and cause substantial instruction-cache pollution. Throw-helper methods such as ArgumentNullException.ThrowIfNull are simpler and more efficient than if blocks that construct a new exception instance.
Example
The following code snippet shows a violation of CA1510:
void M(string arg)
{
    if (arg is null)
        throw new ArgumentNullException(nameof(arg));
}
The following code snippet shows the fix:
void M(string arg)
{
    ArgumentNullException.ThrowIfNull(arg);
}
How to fix violations
Replace the if block that throws the exception with a call to ArgumentNullException.ThrowIfNull. Or, in Visual Studio, use the lightbulb menu to fix your code automatically.
When to suppress warnings
It's safe to suppress a violation of this rule if you're not concerned about the maintainability of your code. It is also fine to suppress violations that are identified to be false positives.
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 CA1510
// The code that's violating the rule is on this line.
#pragma warning restore CA1510
To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1510.severity = none
For more information, see How to suppress code analysis warnings.