53 lines
1.5 KiB
Plaintext
53 lines
1.5 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 `null`.
|
|
|
|
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.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void Sample(bool condition)
|
|
{
|
|
int? nullableValue = condition ? 42 : null;
|
|
Console.WriteLine(nullableValue.Value); // Noncompliant: InvalidOperationException is raised
|
|
|
|
int? nullableCast = condition ? 42 : null;
|
|
Console.WriteLine((int)nullableCast); // Noncompliant: InvalidOperationException is raised
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
void Sample(bool condition)
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1[Nullable<T>]
|
|
* CWE - https://cwe.mitre.org/data/definitions/476[CWE-476 - NULL Pointer Dereference]
|
|
|
|
include::../rspecator-dotnet.adoc[]
|