Accessing a null value will always throw a NullReferenceException most likely causing an abrupt program
termination.
Such termination might expose sensitive information that a malicious third party could exploit to, for instance, bypass security measures.
Exceptions
In the following cases, the rule does not raise:
Extensions Methods
Calls to extension methods can still operate on null
values.
using System;
using System.Text.RegularExpressions;
public static class Program
{
public static string RemoveVowels(this string value)
{
if (value == null)
{
return null;
}
return Regex.Replace(value, "[aeoui]*","", RegexOptions.IgnoreCase);
}
public static void Main()
{
Console.WriteLine(((string?)null).RemoveVowels()); // Compliant: 'RemoveVowels' is an extension method
}
}
Unreachable code
Unreachable code is not executed, thus null
values will never be accessed.
public void Method()
{
object o = null;
if (false)
{
o.ToString(); // Compliant: code is unreachable
}
}
Validated value by analysis attributes
Nullable analysis attributes enable
the developer to annotate methods with information about the null-state of its arguments. Thus, potential null
values validated by one of
the following attributes will not raise:
It is important to note those attributes are only available starting .NET Core 3. As a workaround, it is possible to define those attributes
manually in a custom class:
using System;
public sealed class NotNullAttribute : Attribute { } // The alternative name 'ValidatedNotNullAttribute' is also supported
public static class Guard
{
public static void NotNull<T>([NotNull] T value, string name) where T : class
{
if (value == null)
{
throw new ArgumentNullException(name);
}
}
}
public static class Utils
{
public static string Normalize(string value)
{
Guard.NotNull(value, nameof(value)); // Will throw if value is null
return value.ToUpper(); // Compliant: value is known to be not null here.
}
}
Validated value by Debug.Assert
A value validated with Debug.Assert to not be
null
is safe to access.
using System.Diagnostics;
public void Method(object myObject)
{
Debug.Assert(myObject != null);
myObject.ToString(); // Compliant: 'myObject' is known to be not null here.
}
Validated value by IDE-specific attributes
Like with null-analysis-attribute, potential null
values validated by one of the following IDE-specific attributes will not raise
Visual Studio
JetBrains Rider
Null forgiving operator
Expression marked with the null forgiving
operator
public void Method()
{
object o = null;
o!.ToString(); // Compliant: the null forgiving operator suppresses the nullable warning
}