Egon Okerman d1417e82f8
Modify CWE and OWASP Top 10 links to follow standard link format (APPSEC-1134) (#3529)
* Fix all CWE references

* Fix all OWASP references

* Fix missing CWE prefixes
2024-01-15 17:15:56 +01:00

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[]