2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-03-22 16:11:32 +01:00
2023-04-14 17:26:06 +02:00
Nullable value types can hold either a value or `Nothing`. 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 the value is accessed to avoid the exception.
2023-03-22 16:11:32 +01:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2023-03-22 16:11:32 +01:00
[source,vbnet]
----
2023-04-14 17:26:06 +02:00
Sub Sample(condition As Boolean)
Dim nullableValue As Integer? = If(condition, 42, Nothing)
Console.WriteLine(nullableValue.Value) ' Noncompliant
2023-03-22 16:11:32 +01:00
2023-04-14 17:26:06 +02:00
Dim nullableCast As Integer? = If(condition, 42, Nothing)
Console.WriteLine(CType(nullableCast, Integer)) ' Noncompliant
End Sub
2023-03-22 16:11:32 +01:00
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2023-03-22 16:11:32 +01:00
[source,vbnet]
----
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
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]