Methods declared as Public
, Protected
, or Protected Friend
can be accessed from other assemblies, which
means you should validate parameters to be within the expected constraints. In general, checking against Nothing
is recommended in
defensive programming.
This rule raises an issue when a parameter of a publicly accessible method is not validated against Nothing
before being
dereferenced.
Noncompliant code example
Public Class Sample
Public Property Message As String
Public Sub PublicMethod(Arg As Exception)
Message = Arg.Message ' Noncompliant
End Sub
Protected Sub ProtectedMethod(Arg As Exception)
Message = Arg.Message ' Noncompliant
End Sub
End Class
Compliant solution
Public Class Sample
Public Property Message As String
Public Sub PublicMethod(Arg As Exception)
If Arg IsNot Nothing Then Message = Arg.Message ' Noncompliant
End Sub
Protected Sub ProtectedMethod(Arg As Exception)
ArgumentNullException.ThrowIfNull(Arg)
Message = Arg.Message ' Noncompliant
End Sub
Private Sub PrivateMethod(Arg As Exception)
Message = Arg.Message ' Compliant: method is not publicly accessible
End Sub
End Class
Exceptions
- Arguments validated for
Nothing
via helper methods should be annotated with the [NotNull
] attribute.
- Method parameters marked with the
[NotNull]
Resharper code annotation
attribute are supported as well.
- To create a custom null validation method declare an attribute with name
ValidatedNotNullAttribute
and mark the parameter that is
validated for null in your method declaration with it:
Imports System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Parameter, Inherited:=False)>
Public NotInheritable Class ValidatedNotNullAttribute
Inherits Attribute
End Class
Public Module Guard
Public Sub NotNull(Of T As Class)(<ValidatedNotNullAttribute> Value As T, <CallerArgumentExpression("Value")> Optional Name As String = "")
If Value Is Nothing Then Throw New ArgumentNullException(Name)
End Sub
End Module
Public Module SampleUsage
Public Function CustomToUpper(Value As String) As String
Guard.NotNull(Value)
Return Value.ToUpper
End Function
End Module