2023-05-25 14:18:12 +02:00
== Why is this an issue?
2023-06-15 11:08:34 +02:00
https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1[Nullable value types] can hold either a value or `null`.
2023-05-25 14:18:12 +02:00
2023-06-15 11:08:34 +02:00
The value held in the nullable type can be accessed with the `Value` property or by casting it to the underlying type. Still, both operations throw an `InvalidOperationException` when the value is `null`. A nullable type should always be tested before accessing the value to avoid raising exceptions.
2023-05-25 14:18:12 +02:00
2023-06-15 11:08:34 +02:00
== How to fix it
2023-05-25 14:18:12 +02:00
2023-06-15 11:08:34 +02:00
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2023-05-25 14:18:12 +02:00
----
2023-06-15 11:08:34 +02:00
void Sample(bool condition)
2023-05-25 14:18:12 +02:00
{
int? nullableValue = condition ? 42 : null;
2023-06-15 11:08:34 +02:00
Console.WriteLine(nullableValue.Value); // Noncompliant: InvalidOperationException is raised
2023-05-25 14:18:12 +02:00
int? nullableCast = condition ? 42 : null;
2023-06-15 11:08:34 +02:00
Console.WriteLine((int)nullableCast); // Noncompliant: InvalidOperationException is raised
2023-05-25 14:18:12 +02:00
}
----
2023-06-15 11:08:34 +02:00
==== Compliant solution
2023-05-25 14:18:12 +02:00
2023-06-15 11:08:34 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2023-05-25 14:18:12 +02:00
----
2023-06-15 11:08:34 +02:00
void Sample(bool condition)
2023-05-25 14:18:12 +02:00
{
int? nullableValue = condition ? 42 : null;
if (nullableValue.HasValue)
{
Console.WriteLine(nullableValue.Value);
}
int? nullableCast = condition ? 42 : null;
if (nullableCast is not null)
{
Console.WriteLine((int)nullableCast);
}
}
----
2023-06-15 11:08:34 +02:00
== Resources
2023-05-25 14:18:12 +02:00
2023-06-15 11:08:34 +02:00
=== Documentation
2021-09-20 15:38:42 +02:00
2023-06-15 11:08:34 +02:00
* https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1[Nullable<T>]
* https://cwe.mitre.org/data/definitions/476[MITRE, CWE-476] - NULL Pointer Dereference
2021-06-02 20:44:38 +02:00
2023-06-15 11:08:34 +02:00
include::../rspecator-dotnet.adoc[]