2022-09-05 08:04:25 +02: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
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
2022-09-05 08:04:25 +02:00
public void Method()
2020-06-30 12:48:07 +02:00
{
2022-09-05 08:04:25 +02:00
object o = null;
Console.WriteLine(o.ToString()); // Noncompliant, always null
2020-06-30 12:48:07 +02:00
}
2022-09-05 08:04:25 +02:00
----
== Compliant Solution
[source,csharp]
----
public void Method()
2020-06-30 12:48:07 +02:00
{
2022-09-05 08:04:25 +02:00
var o = new object();
Console.WriteLine(o.ToString());
2020-06-30 12:48:07 +02:00
}
----
== Exceptions
2022-09-05 08:04:25 +02:00
Calls to extension methods are not reported because they can still operate on `null` values.
2021-02-02 15:02:10 +01:00
2022-09-05 08:04:25 +02: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 14:49:38 +02:00
2022-09-05 08:04:25 +02:00
[source,csharp]
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[]
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]