A reference to null should never be dereferenced/accessed. Doing so will cause a NullReferenceException to be thrown. At
best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or
it could allow an attacker to bypass security measures.
public void Method()
{
object o = null;
Console.WriteLine(o.ToString()); // Noncompliant, always null
}
public void Method()
{
var o = new object();
Console.WriteLine(o.ToString());
}
Calls to extension methods are not reported because they can still operate on null values.
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:
using System;
public sealed class ValidatedNotNullAttribute : Attribute { }
public static class Guard
{
public static void NotNull<T>([ValidatedNotNull] this T value, string name) where T : class
{
if (value == null)
throw new ArgumentNullException(name);
}
}
public static class Utils
{
public static string ToUpper(string value)
{
Guard.NotNull(value, nameof(value));
if (value == null)
{
return value.ToString(); // Compliant, this code is not reachable
}
return value.ToUpper();
}
}