2023-05-03 11:06:20 +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 `Nothing`.
2023-03-22 16:11:32 +01:00
2023-06-15 11:08:34 +02:00
The value stored 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 `Nothing`. A nullable type should always be tested before accessing the value to avoid raising exceptions.
2023-03-22 16:11:32 +01:00
2023-06-15 11:08:34 +02:00
== How to fix it
2023-03-22 16:11:32 +01:00
2023-06-15 11:08:34 +02:00
=== Code examples
==== Noncompliant code example
[source,vbnet,diff-id=1,diff-type=noncompliant]
2023-03-22 16:11:32 +01:00
----
2023-04-14 17:26:06 +02:00
Sub Sample(condition As Boolean)
Dim nullableValue As Integer? = If(condition, 42, Nothing)
2023-06-15 11:08:34 +02:00
Console.WriteLine(nullableValue.Value) ' Noncompliant: InvalidOperationException is raised
2023-03-22 16:11:32 +01:00
2023-04-14 17:26:06 +02:00
Dim nullableCast As Integer? = If(condition, 42, Nothing)
2023-06-15 11:08:34 +02:00
Console.WriteLine(CType(nullableCast, Integer)) ' Noncompliant: InvalidOperationException is raised
2023-04-14 17:26:06 +02:00
End Sub
2023-03-22 16:11:32 +01:00
----
2023-06-15 11:08:34 +02:00
==== Compliant solution
2023-03-22 16:11:32 +01:00
2023-06-15 11:08:34 +02:00
[source,vbnet,diff-id=1,diff-type=compliant]
2023-03-22 16:11:32 +01:00
----
2023-04-14 17:26:06 +02:00
Sub Sample(condition As Boolean)
Dim nullableValue As Integer? = If(condition, 42, Nothing)
If nullableValue.HasValue Then
Console.WriteLine(nullableValue.Value)
End If
Dim nullableCast As Integer? = If(condition, 42, Nothing)
If nullableCast.HasValue Then
Console.WriteLine(CType(nullableCast, Integer))
End If
End Sub
2023-03-22 16:11:32 +01:00
----
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
2023-03-22 16:11:32 +01: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
2023-03-22 16:11:32 +01:00
2023-06-15 11:08:34 +02:00
include::../rspecator-dotnet.adoc[]