org.sonar.plugins.csharp.S3655.html Maven / Gradle / Ivy
Why is this an issue?
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
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
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
© 2015 - 2024 Weber Informatics LLC | Privacy Policy