rspec/rules/S2259/csharp/rule.adoc

61 lines
1.6 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
----
object o = null;
if (condition)
{
M1(o.ToString()); // Noncompliant, always null
}
else
{
o = new object();
}
M2(o.ToString());
----
== Exceptions
2021-01-27 13:42:22 +01:00
Calls to extension methods are not reported because they can still operate on ``++null++`` values.
2020-06-30 12:48:07 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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:
2020-06-30 12:48:07 +02:00
----
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[]
ifdef::env-github,rspecator-view[]
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]