All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null.
If a method can be called from an unknown assembly because it is declared public or protected, you should validate all parameters of the method. If the method is designed to be called only by known assemblies, mark the method internal and apply the InternalsVisibleToAttribute attribute to the assembly that contains the method.
How to fix violations
To fix a violation of this rule, validate each reference argument against null.
When to suppress warnings
You can suppress a warning from this rule if you are sure that the dereferenced parameter has been validated by another method call in the function.
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.
C#
#pragmawarning disable CA1062// The code that's violating the rule is on this line.#pragmawarning restore CA1062
To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
These options can be configured for just this rule, for all rules they apply to, or for all rules in this category (Design) that they apply to. For more information, see Code quality rule configuration options.
Include specific API surfaces
You can configure which parts of your codebase to run this rule on, based on their accessibility, by setting the api_surface option. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:
Replace the XXXX part of CAXXXX with the ID of the applicable rule.
Napomena
This option is supported for CA1062 in .NET 7 and later versions only.
Exclude specific symbols
You can exclude specific symbols, such as types and methods, from analysis by setting the excluded_symbol_names option. For example, to specify that the rule should not run on any code within types named MyType, add the following key-value pair to an .editorconfig file in your project:
Replace the XXXX part of CAXXXX with the ID of the applicable rule.
Allowed symbol name formats in the option value (separated by |):
Symbol name only (includes all symbols with the name, regardless of the containing type or namespace).
Fully qualified names in the symbol's documentation ID format. Each symbol name requires a symbol-kind prefix, such as M: for methods, T: for types, and N: for namespaces.
.ctor for constructors and .cctor for static constructors.
Matches specific methods MyMethod1 and MyMethod2 with the respective fully qualified signatures.
Exclude specific types and their derived types
You can exclude specific types and their derived types from analysis by setting the excluded_type_names_with_derived_types option. For example, to specify that the rule should not run on any methods within types named MyType and their derived types, add the following key-value pair to an .editorconfig file in your project:
Matches specific types MyType1 and MyType2 with the respective fully qualified names, and all of their derived types.
Exclude extension method 'this' parameter
By default, this rule analyzes and flags the this parameter for extension methods. You can exclude analysis of the this parameter for extension methods by adding the following key-value pair to an .editorconfig file in your project:
This rule can lead to false positives if your code calls special null-check validation methods in referenced libraries or projects. You can avoid these false positives by specifying the name or signature of null-check validation methods. The analysis assumes that arguments passed to these methods are non-null after the call. For example, to mark all methods named Validate as null-check validation methods, add the following key-value pair to an .editorconfig file in your project:
Matches specific methods Validate1 and Validate2 with respective fully qualified signature.
Example 1
The following example shows a method that violates the rule and a method that satisfies the rule.
C#
using System;
namespaceDesignLibrary
{
publicclassTest
{
// This method violates the rule.publicvoidDoNotValidate(string input)
{
if (input.Length != 0)
{
Console.WriteLine(input);
}
}
// This method satisfies the rule.publicvoidValidate(string input)
{
if (input == null)
{
thrownew ArgumentNullException(nameof(input));
}
if (input.Length != 0)
{
Console.WriteLine(input);
}
}
}
}
Imports System
Namespace DesignLibrary
Public Class Test
' This method violates the rule.
Sub DoNotValidate(ByVal input As String)
If input.Length <> 0 Then
Console.WriteLine(input)
End If
End Sub
' This method satisfies the rule.
Sub Validate(ByVal input As String)
If input Is Nothing Then
Throw New ArgumentNullException(NameOf(input))
End If
If input.Length <> 0 Then
Console.WriteLine(input)
End If
End Sub
End Class
End Namespace
Example 2
Copy constructors that populate fields or properties that are reference objects can also violate rule CA1062. The violation occurs because the copied object that's passed to the copy constructor might be null (Nothing in Visual Basic). To resolve the violation, use a static (Shared in Visual Basic) method to check that the copied object is not null.
In the following Person class example, the other object that is passed to the Person copy constructor might be null.
C#
publicclassPerson
{
publicstring Name { get; privateset; }
publicint Age { get; privateset; }
publicPerson(string name, int age)
{
Name = name;
Age = age;
}
// Copy constructor CA1062 fires because other is dereferenced// without being checked for nullpublicPerson(Person other)
: this(other.Name, other.Age)
{
}
}
Example 3
In the following revised Person example, the other object that's passed to the copy constructor is first checked for null in the PassThroughNonNull method.
C#
publicclassPerson
{
publicstring Name { get; privateset; }
publicint Age { get; privateset; }
publicPerson(string name, int age)
{
Name = name;
Age = age;
}
// Copy constructorpublicPerson(Person other)
: this(PassThroughNonNull(other).Name, other.Age)
{
}
// Null check methodprivatestatic Person PassThroughNonNull(Person person)
{
if (person == null)
thrownew ArgumentNullException(nameof(person));
return person;
}
}
Surađujte s nama na GitHubu
Izvor za ovaj sadržaj možete pronaći na GitHubu, gdje možete stvarati i pregledavati probleme i zahtjeve za povlačenjem. Dodatne informacije potražite u našem vodiču za suradnike.
Povratne informacije o proizvodu .NET
.NET je projekt otvorenog koda. Odaberite vezu za slanje povratnih informacija:
Pridružite se seriji susreta kako biste s kolegama programerima i stručnjacima izgradili skalabilna rješenja umjetne inteligencije temeljena na stvarnim slučajevima upotrebe.