rspec/rules/S3655/vbnet/rule.adoc
Costin Zaharia ea3ad82654
Modify rule S3655: LaYC format (#2204)
## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
2023-06-15 11:08:34 +02:00

49 lines
1.6 KiB
Plaintext

== Why is this an issue?
https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1[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 accessing the value to avoid raising exceptions.
== How to fix it
=== Code examples
==== Noncompliant code example
[source,vbnet,diff-id=1,diff-type=noncompliant]
----
Sub Sample(condition As Boolean)
Dim nullableValue As Integer? = If(condition, 42, Nothing)
Console.WriteLine(nullableValue.Value) ' Noncompliant: InvalidOperationException is raised
Dim nullableCast As Integer? = If(condition, 42, Nothing)
Console.WriteLine(CType(nullableCast, Integer)) ' Noncompliant: InvalidOperationException is raised
End Sub
----
==== Compliant solution
[source,vbnet,diff-id=1,diff-type=compliant]
----
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
=== Documentation
* 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
include::../rspecator-dotnet.adoc[]