rspec/rules/S2259/csharp/rule.adoc
2021-01-27 13:42:22 +01:00

53 lines
1.4 KiB
Plaintext

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.
== Noncompliant Code Example
----
object o = null;
if (condition)
{
M1(o.ToString()); // Noncompliant, always null
}
else
{
o = new object();
}
M2(o.ToString());
----
== Exceptions
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();
}
}
----
include::../see.adoc[]