Why is this an issue?
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.
Noncompliant code example
Sub Sample(condition As Boolean)
Dim nullableValue As Integer? = If(condition, 42, Nothing)
Console.WriteLine(nullableValue.Value) ' Noncompliant
Dim nullableCast As Integer? = If(condition, 42, Nothing)
Console.WriteLine(CType(nullableCast, Integer)) ' Noncompliant
End Sub
Compliant solution
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
Resources